Given two strings s and t , write a function to determine if t is an anagram of s.
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 * 104
s
and t
consist of lowercase English letters.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
m = [0] * 26
for ch in s:
m[ord(ch) - 97] += 1
for ch in t:
m[ord(ch) - 97] -= 1
for i in m:
if i != 0:
return False
return True
''' Fast version '''
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return set(Counter(s).items()) == set(Counter(t).items())
''' Short version '''
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
func isAnagram(s string, t string) bool {
if len(s) != len(t) {
return false
}
var count [26]int
for _, c := range s {
count[c-'a']++
}
for _, c := range t {
count[c-'a']--
if count[c-'a'] < 0 {
return false
}
}
return true
}
|