LeetCode--Group Anagrams

LeetCode——Group Anagrams

Question

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:

[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note: All inputs will be in lower-case.

解题思路

首先,想到的就是两个for循环一次比较,判断的时候,可以将两个字符串按照字母序排序,来判断两个是否相当,两个for循环,数量多的时候肯定是要超时的。时间复杂度为O(n^2).

所以,这个道题考的是Hash算法,用Map实现,时间复杂度为O(n)。

具体实现

  1. 一般解法:
#include <iostream>
#include <vector>
#include <map>

using namespace std;

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        if (strs.empty())
            return vector<vector<string> >();

        int len = strs.size();

        vector<vector<string> > ret;

        for (int i = 0; i < len; i++)
        {
            if (strs[i].empty())
                continue;
            vector<string > sv;
            string tmp1 = strs[i];
            sv.push_back(tmp1);

            sort(tmp1.begin(), tmp1.end());
            for (int j = i + 1; j < len; j++)
            {
                string tmp2 = strs[j];
                sort(tmp2.begin(), tmp2.end());

                if (tmp1 == tmp2)
                {
                    sv.push_back(strs[j]);
                    //将处理后的元素赋值为空
                    strs[j].erase(0, std::string::npos);
                }
            }//for

            //按字典排序该序列
            sort(sv.begin(), sv.end());
            //添加到结果vector
            ret.push_back(sv);

        }//for
        return ret;
    }
};


int main() {
    vector<string> vec;
    vec.push_back("");
    vec.push_back("tea");
    vec.push_back("tan");
    vec.push_back("ate");
    vec.push_back("nat");
    vec.push_back("bat");
    Solution* solution = new Solution();
    vector<vector<string>> result = solution->groupAnagrams(vec);
    for (int i = 0; i < result.size(); i++) {
        for (int j = 0; j < result[i].size(); j++) {
            cout << result[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}
  1. AC解法:
#include <iostream>
#include <vector>
#include <map>

using namespace std;

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        if (strs.size() == 0)
            return vector<vector<string>>();
        int size = strs.size();

        vector<vector<string>> res;

        map<string, vector<string>> str_vec;
        for (int i = 0; i < size; i++) {
            string str = strs[i];
            sort(str.begin(), str.end());
            str_vec[str].push_back(strs[i]);
        }
        for (map<string, vector<string>>::iterator iter = str_vec.begin(); iter != str_vec.end(); iter++) {
            sort(iter->second.begin(), iter->second.end());
            res.push_back(iter->second);
        }
        return res;
    }
};
posted @ 2017-03-18 15:41  清水汪汪  阅读(185)  评论(0编辑  收藏  举报