Leetcode刷题Day10|有效的字母异位词
1.题目描述
给定两个字符串 s
和 t
,编写一个函数来判断 t
是否是 s
的 字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
提示:
1 <= s.length, t.length <= 5 * 104
s
和t
仅包含小写字母
2.题解
哈希表
class Solution {
public:
bool isAnagram(string s, string t) {
std::unordered_map<char,int> count;
for(char c:s){
count[c]++;
}
for(char c:t){
if(count[c]==0)return false;
count[c]--;
}
for(char c:s){
if(count[c]!=0)return false;
}
return true;
}
};
思路
使用哈希表先统计s中字母频率,存入count,再遍历t,如果t中有s中没有的字母,返回false,如果存在相同字母,count中减1,最后遍历s,如果不全为0,就返回false,全为0就返回true。
复杂度
- 时间复杂度: O(n)
- 空间复杂度: O(n)