面试碰到这个算法:字母异位词分组
生活随笔
收集整理的這篇文章主要介紹了
面试碰到这个算法:字母异位词分组
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? 題目:輸入: ["eat", "tea", "tan", "ate", "nat", "bat"]
? ? ? 輸出:
? ? ? [
? ? ? ? ?["ate","eat","tea"],
? ? ? ? ?["nat","tan"],
? ? ? ? ?["bat"]
? ? ? ]
方法1:先將每個字符串進行排序,然后判斷是否相等
class Solution { public:vector<vector<string>> groupAnagrams(vector<string>& strs) {//用于計數表示是第幾個元素unordered_map<string,int> m;vector<vector<string>> res;string temp;int pos=0;//遍歷vectorfor(auto i:strs) {temp = i;//排序sort(temp.begin(),temp.end());if(m.find(temp) == m.end()) {vector<string> v(1,i);res.push_back(v);m[temp] = pos++;}else {res[m[temp]].push_back(i);}}return res;} };方法2:按計數分類,記錄每個字符串中每個字符出現的次數,如果字母出現的次數一樣則說明兩個字符串是異位的
?
總結
以上是生活随笔為你收集整理的面试碰到这个算法:字母异位词分组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: you-get工具
- 下一篇: 超经典动态规划题:最大子序和