題目鏈接:https://leetcode.cn/problems/group-anagrams/
思路如下:
輸入:strs = [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
對每個字符串進行排序:strs = [“aet”, “aet”, “ant”, “aet”, “ant”, “abt”]
如果排序后的字符串相同,則將它們歸為同一組:[[“bat”],[“nat”,“tan”],[“ate”,“eat”,“tea”]]
C++代碼如下:
class Solution {public:
vector>groupAnagrams(vector& strs) {unordered_map>str2vec;
for (auto& str : strs) {auto tmp = str;
sort(tmp.begin(), tmp.end());
str2vec[tmp].push_back(str);
}
vector>res;
for (auto& item : str2vec) {res.push_back(item.second);
}
return res;
}
};
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧