242. 有效的字母异位词 && 49. 字母异位词分组

242. 有效的字母异位词

描述

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
说明:
所有输入均为小写字母。
不考虑答案输出的顺序。

思路

  • 方法1 对数组进行排序,排序后的字符串相等则为字母异位词
class Solution {
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(),s.end());
        sort(t.begin(),t.end());
        if(s==t)
            return true;
        else
            return false;
    }
};
  • 方法2 哈希表
    使用26位计数表统计每个字母出现的次数,s出现一次+1,t出现一次-1
class Solution {
public:
    bool isAnagram(string s, string t) {
        int count[26]={0};
        int sl=s.length();
        int tl=t.length();
        if(sl!=tl)
            return false;
        for(int i=0;i<sl;++i){
            ++count[s[i]-'a'];
            --count[t[i]-'a'];
        }
        for(auto iter:count){
            if(iter!=0)
                return false;
        }
        return true;
    }
};

49. 字母异位词分组

描述

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]

说明:
所有输入均为小写字母。
不考虑答案输出的顺序。

思路

使用排序后的字符串作索引,加入到map中,值为字符串数组。

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> res;
        map<string,vector<string>> mp;
        for(auto s:strs){
            string t=s;
            sort(t.begin(),t.end());
            mp[t].push_back(s);
        }
        for(auto s:mp){
            res.push_back(s.second);
        }
        return res;
    }
};
posted @ 2020-04-19 23:07  hunter-w  阅读(105)  评论(0编辑  收藏  举报