49. Group Anagrams

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:

  1. For the return value, each inner list's elements must follow the lexicographic order.
  2. All inputs will be in lower-case.

分析:

仔细观察会发现,"ate", "eat","tea"排完序之后都是“ate”,

利用哈希表,将排完序的字符串在哈希表中查找,并且保存他进入哈希表的顺序位置。

比如例子中,如果当前排序后的字符串不存在哈希时就压入哈希(以下为遍历完的结果)

mapping["ate"]=0,

mapping["nat"]=1,

mapping["bat"]=2,

显然0这个位置就是所有移位"ate", "eat","tea"字符串所在result二维数组中的第一行

同理1这个位置就是所有移位"nat","tan"字符串所在result二维数组中的第二行

同理2这个位置就是"bat"字符串所在result二维数组中的第三行


最后值得注意的是题目要求每一行都是字典顺序,记得最后对每一行字符串排序。

具体代码如下:

class Solution {
public:
    vector> groupAnagrams(vector& strs) {
        vector> result;
            
        unordered_map mapping;
        string tmpstr;
        for(int i=0;i tmpvec; 
                tmpvec.push_back(strs[i]);
                result.push_back(tmpvec);//申请新一行,它将是其他移位字符串的开端
            }
            else//我们已经为排序后为tmpstr的字符串申请了该行
                result[mapping[tmpstr]].push_back(strs[i]);//注意这个mapping[tmpstr]位置值在result中的关系
        }
        // 一次对每一个子vector中的单词进行排序。
        for (int i = 0; i < result.size(); ++i) 
            sort(result[i].begin(), result[i].end());
        return result;
    }
};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50726724

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

你可能感兴趣的:(LeetCode,OJ,LeetCode解题报告)