leetcode242 Anagram
Given two strings s and t, write a function to determine if t is an alphabetic word of s.
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-anagram
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Example:
1、
Input: s = “anagram”, t = “nagaram”
Output: true
2、
Input: s = “rat”, t = “car”
Output: false
Thought and method:
To this question, we may have several ways.
1、sort and verify
It is a easy and simple way to think of. We can obviously get the two same strings after sorting if they are anagrams.
However, it is not so appropriate to use it in the Go due to the high time and space consume.Besides, other ways are better.
Time complexity: O(nlogn)
Space complexity: O(1)
2、use harsh
We can simply use a counter to add the numbers of 26 letters showing in the string s, and then subtract the number of 26 letters in the string t.
Finally, counter equals 0 leading to “true” while other numbers leading to “False”
3、similar to harsh but only use array
Considering 26 letters, we can do some change. Using to counters to add the numbers of 26 letters in both strings. If they are equal, the resuly must be “true”.
Surprisingly, using only array actually raise the perfomance in time despite the same Algorithm ideas in two ways.
Both
Time complexity: O(n)
Space complexity: O(1)
Code:
2、
func isAnagram(s string, t string) bool {
if len(s) != len(t) {
return false
}
Counter := make(map[string]int)
for i := 0; i < len(s); i++ {
Counter[string(s[i])] ++
}
for j := 0; j < len(t); j ++ {
Counter[string(t[j])] --
}
for _, m := range Counter {
if m != 0 {
return false
}
}
return true
}
3、
func isAnagram(s string, t string) bool {
a := [26]int{}
b := [26]int{}
for _, v := range s {
a[v-'a'] ++
}
for _, v := range t {
b[v-'a'] ++
}
return a == b
}
Test
Input: s = “anagram”, t = “nagaram”
Input: s = “rat”, t = “car”
leetcode comparison of operation results
The former one uses way 2, the latter one uses way 3