242.Valid Anagram
242.Valid Anagram
难度:Easy
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。
进阶: 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
可以使用map映射比较,由于一共24个小写字母,也可以直接使用数组比较。
class Solution {
public:
bool isAnagram(string s, string t) {
int s1[26]={0};
int t1[26]={0};
for(auto c:s)
s1[c-'a']++;
for(auto c:t)
t1[c-'a']++;
for(int i=0;i<26;i++)
if(s1[i]!=t1[i]) return false;
return true;
}
};
执行用时 : 12 ms, 在Valid Anagram的C++提交中击败了97.08% 的用户 内存消耗 : 9.5 MB, 在Valid Anagram的C++提交中击败了8.77% 的用户
Last updated
Was this helpful?