242 有效的字母异位词

本文最后更新于:2022年8月30日 晚上

给定两个字符串 st ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1:

1
2
输入: s = "anagram", t = "nagaram"
输出: true

示例 2:

1
2
输入: s = "rat", t = "car"
输出: false

说明:
你可以假设字符串只包含小写字母。

进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

Solution

  • 利用 unordered_map
  • 因为字符a到字符z的ASCII是26个连续的数值,所以可以用数组作为哈希表。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// @lc code=start
class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<int, int> record;
for(char c : s)
record[c] += 1;

for(char c : t){
if(record[c]>0)
record[c] -= 1;
else
return false;
}

for(auto it=record.begin(); it!=record.end();++it){
if(it->second != 0)
return false;
}
return true;
}
};
// @lc code=end
  • 直接比较两个 map 是否相等。。。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<int, int> record1, record2;
for(char c : s)
record1[c] += 1;
for(char c : t)
record2[c] += 1;
if(record1==record2)
return true;
else
return false;
}
};

java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public boolean isAnagram(String s, String t) {
int[] record = new int[26];

for (char c : s.toCharArray()) {
record[c - 'a'] += 1;
}
for (char c : t.toCharArray()) {
record[c - 'a'] -= 1;
}
for (int i : record) {
if (i != 0) {
return false;
}
}
return true;
}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!