有效的字母异位词
描述
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 1:
输入: s = “anagram”, t = “nagaram”
输出: true
示例 2:
输入: s = “rat”, t = “car”
输出: false
思路和代码
思路1:哈希
- 首先判断s和t长度相等不相等,不相等直接返回false
- 然后定义一个26长度的数组,遍历s和t的每一个元素。给数组相应位置加1或减1
- 最后再遍历一遍,如果是异位词最后的数组肯定所有元素都为0
class Solution {
public:
bool isAnagram(string s, string t) {
int num[26] = {0};
int lenS = s.size();
int lenT = t.size();
if(lenS != lenT)
return false;
for(int i=0; i<lenS; i++)
{
num[s[i] - 'a']++;
num[t[i] - 'a']--;
}
for(int i=0; i<26; i++)
{
if(num[i] != 0)
return false;
}
return true;
}
};
更简洁的代码思路如下:
直接给s和t排序,直接判断排序后相等不相等。当然这一种时间效率远不如上面,因为排序很消耗时间。
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
字母异位词分组
描述
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
思路和代码
这一题比上一题难,但是方法是类似的,用哈希表来存字母异位词相同的那些单词。
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<string, vector<string>> res;
int n = strs.size();
for(int i=0; i<n; i++)
{
string temp = strs[i];
sort(temp.begin(), temp.end());
res[temp].push_back(strs[i]);
}
vector<vector<string>> ans;
for(auto i : res)
ans.push_back(i.second);
return ans;
}
};