File tree 2 files changed +83
-2
lines changed
solution/1000-1099/1002.Find Common Characters
2 files changed +83
-2
lines changed Original file line number Diff line number Diff line change 54
54
55
55
```
56
56
57
- ### ** ...**
58
- ```
57
+ ### ** Go**
58
+ ``` go
59
+ func commonChars (A []string ) []string {
60
+ if len (A) == 0 {
61
+ return []string {}
62
+ }
63
+ res := make ([]int , 26 )
64
+ // 以第一个字符串为基准,先统计出现次数
65
+ for _ , c := range A[0 ] {
66
+ res[c - ' a' ]++
67
+ }
68
+ for i := 1 ; i < len (A); i++ {
69
+ tmp := make ([]int , 26 )
70
+ // 统计后续每个字符串的字符出现次数
71
+ for _ , c := range A[i] {
72
+ tmp[c - ' a' ]++
73
+ }
74
+ // 比较,取小
75
+ for j := 0 ; j < 26 ; j++ {
76
+ res[j] = getMin (res[j], tmp[j])
77
+ }
78
+ }
79
+ // 遍历res,取出字符转换为string数组元素
80
+ result := make ([]string ,0 )
81
+ for i := 0 ; i < len (res); i++ {
82
+ if res[i] > 0 {
83
+ for j := 0 ; j < res[i]; j++ {
84
+ result = append (result, string (' a' + i))
85
+ }
86
+ }
87
+ }
88
+ return result
89
+ }
90
+
91
+ func getMin (a ,b int ) int {
92
+ if a > b{
93
+ return b
94
+ }
95
+ return a
96
+ }
59
97
60
98
```
61
99
Original file line number Diff line number Diff line change
1
+ func commonChars (A []string ) []string {
2
+ if len (A ) == 0 {
3
+ return []string {}
4
+ }
5
+ res := make ([]int , 26 )
6
+ //以第一个字符串为基准,先统计出现次数
7
+ for _ , c := range A [0 ] {
8
+ res [c - 'a' ]++
9
+ }
10
+ for i := 1 ; i < len (A ); i ++ {
11
+ tmp := make ([]int , 26 )
12
+ //统计后续每个字符串的字符出现次数
13
+ for _ , c := range A [i ] {
14
+ tmp [c - 'a' ]++
15
+ }
16
+ //比较,取小
17
+ for j := 0 ; j < 26 ; j ++ {
18
+ res [j ] = getMin (res [j ], tmp [j ])
19
+ }
20
+ }
21
+ //遍历res,取出字符转换为string数组元素
22
+ result := make ([]string ,0 )
23
+ for i := 0 ; i < len (res ); i ++ {
24
+ if res [i ] > 0 {
25
+ for j := 0 ; j < res [i ]; j ++ {
26
+ result = append (result , string ('a' + i ))
27
+ }
28
+ }
29
+ }
30
+ return result
31
+ }
32
+
33
+ func getMin (a ,b int ) int {
34
+ if a > b {
35
+ return b
36
+ }
37
+ return a
38
+ }
39
+
40
+
41
+
42
+
43
+
You can’t perform that action at this time.
0 commit comments