(hash) leetcode 49. Group Anagrams

Thinking: hash table, implemented map, (key, value) = (strs [i], index).

After the string in the lexicographic ordering, if the corresponding character string found in the map, then the corresponding value + 1 (value stored in the word is isomorphic collection of output index), such as [ "ate", " eat "," tea "] corresponding to index 0; [" nat ", tan"] corresponding to index 1 ...

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        //hash
        vector<vector<string>> result;
        map<string, int> index;
        int cnt = 0;   //记录anagram 个数
        for(int i=0; i<strs.size(); ++i){
            string tmp = strs[i];
            sort(tmp.begin(), tmp.end());  // press lexicographic order 
            IF (index.find (tmp) == index.end ()) {
                 // is not found in the map tmp 
                index [tmp] = CNT; 
                CNT ++ ; 
                Vector < String > tmpStr; 
                tmpStr. push_back (STRs [I]); 
                result.push_back (tmpStr); 
            } 
            the else 
                Result [index [tmp]] push_back (STRs [I]);. 
        } 
        return Result; 
    } 
};
class Solution {
 public : 
    Vector <Vector < String >> groupAnagrams (Vector < String > & STRs) { 
        Vector <Vector < String >> RES;     // Return value 
        unordered_map < String , Vector < String >> m;    // string mapping between its homogeneous character string 
        for ( string STR: STRs) {
             string T = STR; 
            Sort (t.begin (), t.end ()); 
            m [T] .push_back (STR); 
        } 
        for  (Auto A: m)
            res.push_back (a.second);
        return res;
    }
};

 

Guess you like

Origin www.cnblogs.com/Bella2017/p/11260514.html