leetCode-0242_有效的字母异位词

题目描述

英文题目

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

1
2
Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

1
2
Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

中文题目

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

示例 1:

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

示例 2:

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

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

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

解决方法

方法一
  • 描述

我们先判断两个字符串长度是否相同,不相同直接返回false。然后把s中所有的字符出现个数统计起来,存入一个大小为26的数组中,因为题目中限定了输入字符串为小写字母组成。然后我们再来统计t字符串,如果发现不匹配则返回false

  • 源码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
bool isAnagram(char* s, char* t) {
int sLen = (int)strlen(s);
int tLen = (int)strlen(t);
if (sLen != tLen) {
return false;
}

int m[26] = {0};
for (int i = 0; i < sLen; i++) {
m[s[i] - 'a'] += 1;
}

for (int i = 0; i < tLen; i++) {
m[t[i] - 'a'] -= 1;
if (m[t[i] - 'a'] < 0) {
return false;
}
}

return true;
}

题目来源

Valid Anagram

有效的字母异位词