49:Anagrams【哈希】【字符串】

題目鏈接:click~

/*題意:給出很多單詞,輸出所有的變位詞
  變位詞:單詞中的字符排序完以後是相同的*/

/**
 *思路:1)從strs的第一個元素開始遍歷,排序得到tmp
 *      2)查看tmp是否在map中
 *      3)若不存在,將(tmp,i)存入map中
 *      4)若存在,通過保存的下標將第一次出現tmp的字符串加入res中,
 *        再將下標設置爲-1,放置重複加入
 */


class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        vector<string> res;
        map<string, int> mp;
        int len = strs.size();
        for(int i = 0; i < len; i ++) {
            string tmp = strs[i];
            sort(tmp.begin(), tmp.end());//排序

            if(mp.find(tmp) == mp.end()) {//不存在,插入
                mp[tmp] = i;
            }
            else {
                if(mp[tmp] >= 0) {
                    //將第一個出現的單詞插入
                    res.push_back(strs[mp[tmp]]);
                    mp[tmp] = -1;
                }
                res.push_back(strs[i]);
            }
        }
        return res;
    }
};


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