242.有效的字母异位词

242. 有效的字母异位词 - 力扣(LeetCode)

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

示例 1: 输入: s = “anagram”, t = “nagaram” 输出: true

示例 2: 输入: s = “rat”, t = “car” 输出: false

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

思路

错误思路:本题不可以对两个字符串中的字符asc码分别相加,判断是否相等来做。因为字符串中的字符不相等,asc码相加的结果也可能是相同的。

正确思路:构建hash表,构建hash function,一个字符串写入数据,另一个字符串删除数据,判断hash表中的元素是否为0。(前提是hash初始化,存储的所有元素都为0)

本题所需要构造的hash表较小,且数据范围也小,因此使用数组来构建hash表。

c语言代码实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

bool isAnagram(char* s, char* t) {
int i ;
int hash[26];
memset(hash,0,sizeof(hash));
for(i=0;i<strlen(s);i++){
hash[ s[i] - 'a']++;
}
for(i=0;i<strlen(t);i++){
hash[ t[i] - 'a']--;
}
for(i= 0;i<26;i++){
if(hash[i] != 0)
return false;
}
return true;
}

c++实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
bool isAnagram(string s, string t) {
int record[26] = {0};
for (int i = 0; i < s.size(); i++) {
// 并不需要记住字符a的ASCII,只要求出一个相对数值就可以了
record[s[i] - 'a']++;
}
for (int i = 0; i < t.size(); i++) {
record[t[i] - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (record[i] != 0) {
// record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。
return false;
}
}
// record数组所有元素都为零0,说明字符串s和t是字母异位词
return true;
}
};