-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path242-ValidAnagram.go
More file actions
74 lines (64 loc) · 1.85 KB
/
242-ValidAnagram.go
File metadata and controls
74 lines (64 loc) · 1.85 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
// 242. Valid Anagram
// 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 * 10^4
// 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 a case?
import "fmt"
// 支持 utf8
func isAnagram(s string, t string) bool {
if len(t) != len(s) {
return false
}
// 逐字写到 map中
ms := make(map[rune]int)
mt := make(map[rune]int)
for _, v := range s {
ms[v]++
}
for _, v := range t {
mt[v]++
}
// 数量出现不一,返回 false
for k,v := range ms {
if v != mt[k] {
return false
}
}
return true
}
// best solution
func isAnagram1(s string, t string) bool {
if len(s) != len(t) {
return false
}
cnt := make([]int, 26)
for i := range s {
cnt[s[i] - 'a'] ++
cnt[t[i] - 'a'] --
}
for i := range cnt {
if cnt[i] != 0 {
return false
}
}
return true
}
func main() {
fmt.Println(isAnagram("anagram","nagaram")) // true
fmt.Println(isAnagram("rat","car")) // false
fmt.Println(isAnagram("bluefrog","leetcode")) // false
fmt.Println(isAnagram("leetcode","bluefrog")) // false
fmt.Println(isAnagram1("anagram","nagaram")) // true
fmt.Println(isAnagram1("rat","car")) // false
fmt.Println(isAnagram1("bluefrog","leetcode")) // false
fmt.Println(isAnagram1("leetcode","bluefrog")) // false
}