首页 > 其他 > 详细

LeetCode Anagrams

时间:2015-03-08 18:51:31      阅读:302      评论:0      收藏:0      [点我收藏+]

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

题意:给你string的数组,让你求出字符和个数都相同的字符串。

思路:对于每个字符串都排序后,用map标记是否已经加入到答案中。

class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        vector<string> ans;
        map<string, int> mp;
        for (int i = 0; i < strs.size(); i++) {
            string tmp = strs[i];
            sort(tmp.begin(), tmp.end());
            if (mp.find(tmp) == mp.end()) 
                mp[tmp] = i;
            else {
                if (mp[tmp] == -1) 
                    ans.push_back(strs[i]);
                else {
                    ans.push_back(strs[mp[tmp]]);
                    mp[tmp] = -1;
                    ans.push_back(strs[i]);
                }
            }
        }

        return ans;
    }
};



LeetCode Anagrams

原文:http://blog.csdn.net/u011345136/article/details/44134489

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!