[LeetCode]242. Valid Anagram 解题报告(C++)
题目描述
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
题目大意
- 求 t是不是 s的一种排列方式
解题思路
方法1:
- 若t是s的一种重组.
- 二者 字符相同且出现的次数相同.
- 于是将 s中的字符以及出现次数用
map
进行存储 - 然后遍历
t
. 若字符不在s
中.则 false.若在则出现次数– - 最后判断
map
的出现次数是否都为0.
代码实现:
class Solution {
public:
bool isAnagram(string s, string t) {
// t是s的一种排序方式
unordered_map<char, int> m;
for (auto x : s) {
m[x]++;
}
for (auto x : t) {
if (m.count(x) == 0) {
return false;
}
else {
m.at(x)--;
}
}
for (auto p : m) {
if (p.second > 0) {
return false;
}
}
return true;
}
};
方法2:
- 类似于方法1 但是更简洁!
- 用哈希表来记录 出现次数和字符.
s
中字符出现是++,t
中的字符出现是 –- 最后看出现次数是否都为0.
代码实现:
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
int n = s.length();
unordered_map<char, int> counts;
for (int i = 0; i < n; i++) {
counts[s[i]]++;
counts[t[i]]--;
}
for (auto count : counts)
if (count.second) return false;
return true;
}
};
方法3:
- 对于只含有 小写字母.
- 可以用数组来存储.不用
hashmap
代码实现:
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
int n = s.length();
int counts[26] = {0};
for (int i = 0; i < n; i++) {
counts[s[i] - 'a']++;
counts[t[i] - 'a']--;
}
for (int i = 0; i < 26; i++)
if (counts[i]) return false;
return true;
}
};
方法4:
- 排序! 逐一比较!
代码实现:
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};