File tree Expand file tree Collapse file tree 3 files changed +84
-1
lines changed Expand file tree Collapse file tree 3 files changed +84
-1
lines changed Original file line number Diff line number Diff line change
1
+ ## 49 字母异位词分组-中等
2
+
3
+ 题目:
4
+
5
+ 给你一个字符串数组,请你将 ** 字母异位词** 组合在一起。可以按任意顺序返回结果列表。
6
+
7
+ ** 字母异位词** 是由重新排列源单词的所有字母得到的一个新单词。
8
+
9
+
10
+
11
+ ** 解题思路**
12
+
13
+ 所谓字母异位词,就是字母字符个数一样,且出现的次数也一样。
14
+
15
+ 所以我们可以对每个字符串进行计数,统计每个字母出现的次数,并保存在数组中。
16
+
17
+ 进而以数组为 key,进行查找合并。
18
+
19
+ ``` go
20
+ // date 2024/01/24
21
+ // 解法1
22
+ // 字符计数
23
+ func groupAnagrams (strs []string ) [][]string {
24
+ // key = [26]int
25
+ // value = []string
26
+ checkMap := map [[26 ]int ][]string {} // key = [26]int
27
+
28
+ ans := make ([][]string , 0 , 16 )
29
+
30
+ for _ , str := range strs {
31
+ one := toCheck (str)
32
+ checkMap[one] = append (checkMap[one], str)
33
+ }
34
+
35
+ for _ , v := range checkMap {
36
+ ans = append (ans, v)
37
+ }
38
+
39
+ return ans
40
+ }
41
+
42
+ func toCheck (str string ) [26]int {
43
+ res := [26 ]int {}
44
+ for _ , v := range str {
45
+ res[v-' a' ]++
46
+ }
47
+ return res
48
+ }
49
+ ```
50
+
Original file line number Diff line number Diff line change 10
10
11
11
12
12
13
- 分析:
13
+ ** 解题思路 **
14
14
15
15
去除不需要比较的字符,然后双指针首尾对撞。
16
16
@@ -34,5 +34,36 @@ func isPalindrome(s string) bool {
34
34
}
35
35
return true
36
36
}
37
+ // 写法2
38
+ // 双指针,直接在原字符串上操作,只判断字母和数字字符
39
+ func isPalindrome (s string ) bool {
40
+ s = strings.ToLower (s)
41
+ left , right := 0 , len (s)-1
42
+
43
+ for left < right {
44
+ if !isCharNum (s[left]) {
45
+ left++
46
+ continue
47
+ }
48
+ if !isCharNum (s[right]) {
49
+ right--
50
+ continue
51
+ }
52
+ if s[left] != s[right] {
53
+ return false
54
+ }
55
+ left++
56
+ right--
57
+ }
58
+
59
+ return true
60
+ }
61
+
62
+ func isCharNum (x uint8 ) bool {
63
+ if x >= ' a' && x <= ' z' || x >= ' 0' && x <= ' 9' {
64
+ return true
65
+ }
66
+ return false
67
+ }
37
68
```
38
69
Original file line number Diff line number Diff line change 20
20
21
21
双指针,逐位判断。如果相同,继续匹配下一位,否则指向 t 的指针右移下一位。
22
22
23
+ 这就是贪心算法。
24
+
23
25
``` go
24
26
// date 2023/12/11
25
27
func isSubsequence (s string , t string ) bool {
You can’t perform that action at this time.
0 commit comments