Given two strings s and t, write a function to determine if t is an anagram of s.
- You may assume the string contains only lowercase alphabets.
- What if the inputs contain unicode characters? How would you adapt your solution to such case?
- use a real HashTable
Example:
- s = "anagram", t = "nagaram", return true.
- s = "rat", t = "car", return false.
C Solution 1:
bool isAnagram(char* s, char* t) {
int flag[26] = {0};
for (; *s; s++) flag[*s - 'a']++;
for (; *t; t++) flag[*t - 'a']--;
int i;
for (i = 0; i < 26; i++) {
if (flag[i]) return false;
}
return true;
}
C Solution 2:
bool isAnagram(char* s, char* t) {
int flag[256] = {0};
int i, diff = 0;
for (i = 0; s[i] && t[i]; i++) {
if (s[i] == t[i]) continue;
diff += ++flag[s[i]] > 0 ? 1 : -1;
diff += --flag[t[i]] < 0 ? 1 : -1;
}
return s[i] || t[i] ? false : !diff;
}
Python Solution 1:
from collections import Counter
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return Counter(s) == Counter(t)
Summary:
- nothing special.
LeetCode: 242. Valid Anagram





近期评论