Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1
Input: s = "anagram", t = "nagaram"
Output: true
Example 2
Input: s = "rat", t = "car"
Output: false
Constraints
- 1 <= s.length, t.length <= 5 * 10e4
- s and t consist of lowercase English letters.
Solution
字母哈希表,全是小写字母所以可以开一个 26 的数组来存每个字母出现的次数。如果发现两个串出现的字符和次数不一样就返回 false ,否则返回 true。
bool isAnagram(char * s, char * t){
int i, nums[26] = {0};
for (i = 0; s[i]; i++) nums[s[i] - 'a']++;
for (i = 0; t[i]; i++) nums[t[i] - 'a']--;
for (i = 0; i < 26; i++) if (nums[i] != 0) return false;
return true;
}
用 python 想到一种方法,先把字符串拆成列表再排序,如果两个列表相等就返回 True ,否则返回 False。
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
ls = list(s)
lt = list(t)
ls.sort()
lt.sort()
return ls == lt