2018年4月17日 下午3:54
Group Anagrams - LeetCode
- 这道题就是典型的边遍历的同时,我们要做比较复杂的判断,不同的判断下处理方式不同。
- 这里的关键是是使用map来记录我们遍历的过程,或者说遍历的同时维护这map,来保存我们遍历的效果。
- 那么我们如何查看我们的记录(map),这里面最关键的一句话就是
str_map.find(str) == str_map.end()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { public: std::vector<std::vector<std::string>> groupAnagrams(std::vector<std::string>& strs) { std::map<std::string, std::vector<std::string> > str_map; std::vector<std::vector<std::string>> vec; if(strs.size() == 0) return vec; for(int i = 0; i < strs.size(); i++){ std::string str = strs[i]; std::sort(str.begin(), str.end()); if(str_map.find(str) == str_map.end()){ std::vector<std::string> temp_vec; temp_vec.push_back(strs[i]); str_map[str] = temp_vec; } else{ str_map[str].push_back(strs[i]); } } std::map<std::string, std::vector<std::string> > ::iterator it; for(it = str_map.begin(); it != str_map.end(); it++){ vec.push_back((*it).second); } return vec; } };
|