-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCCI0102-CheckPermutation.go
More file actions
80 lines (69 loc) · 1.79 KB
/
LCCI0102-CheckPermutation.go
File metadata and controls
80 lines (69 loc) · 1.79 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
75
76
77
78
79
80
package main
// 面试题 01.02. Check Permutation LCCI
// Given two strings,write a method to decide if one is a permutation of the other.
// Example 1:
// Input: s1 = "abc", s2 = "bca"
// Output: true
// Example 2:
// Input: s1 = "abc", s2 = "bad"
// Output: false
// Note:
// 0 <= len(s1) <= 100
// 0 <= len(s2) <= 100
import "fmt"
func CheckPermutation(s1 string, s2 string) bool {
if s1 == s2 {
return true
}
if len(s1) != len(s2) {
return false
}
// 有问题 遇到 (aa,bb) 这种 就判断不正确
// 计算异或值
// b1, b2 := byte(0), byte(0)
// for i := 0; i < len(s1); i += 1 {
// b1 ^= s1[i]
// b2 ^= s2[i]
// }
// return b1 == b2
// 使用 map
m1 := make(map[byte]int)
m2 := make(map[byte]int)
for i := 0; i < len(s1); i += 1 {
m1[s1[i]] += 1
m2[s2[i]] += 1
}
// 比对判断
for k,v := range(m1) {
if m2[k] != v {
return false
}
}
return true
}
// 只需要一个 map
func CheckPermutation1(s1 string, s2 string) bool {
if len(s1) != len(s2) {
return false
}
hash := make([]int, 26)
for i, c := range s1 {
hash[c - 'a']++; // s1 有就 +
hash[s2[i] - 'a']--; // s2 有就 -
}
for _, v := range hash {
// 如果字符出现不同肯定不为 0
if v != 0 {
return false
}
}
return true
}
func main() {
fmt.Println(CheckPermutation("abc","bca")) // true
fmt.Println(CheckPermutation("abc","bad")) // false
fmt.Println(CheckPermutation("aa","bb")) // false
fmt.Println(CheckPermutation1("abc","bca")) // true
fmt.Println(CheckPermutation1("abc","bad")) // false
fmt.Println(CheckPermutation1("aa","bb")) // false
}