leetCode C++ 49. 字母異位詞分組 給定一個字符串數組,將字母異位詞組合在一起。字母異位詞指字母相同,但排列不同的字符串。

一、思路:

      對每一個字符串排序,然後將這個排序的字符串加到map裏面,對於每一個新遍歷的字符串就和map比較是否相等。

      最開始用map,會出現超時,於是採用hash實現結構的unordered_map就不會超時,在50%的效率左右

二、代碼:

class Solution {
public:
	vector<vector<string>> groupAnagrams(vector<string>& strs) {
		unordered_map<string, int> stringCountMap;
		for (string str : strs) {
			string temp = str;
			sort(temp.begin(), temp.end());
			if (stringCountMap.count(temp) > 0)
			{
				res[stringCountMap[temp]].push_back(str);
			}
			else {
				stringCountMap.insert(pair<string, int>(temp, stringCountMap.size()));
				vector<string> resList = { str };
				res.push_back(resList);
			}
		}
		return res;
	}
private:
	vector<vector<string>> res;
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章