Skip to content

Commit bf52c33

Browse files
committed
49 字母异位词分组
Signed-off-by: subond <yubc0321@gmail.com>
1 parent 1062002 commit bf52c33

File tree

3 files changed

+84
-1
lines changed

3 files changed

+84
-1
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+

05_string/No.125_验证回文串.md

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111

1212

13-
分析:
13+
**解题思路**
1414

1515
去除不需要比较的字符,然后双指针首尾对撞。
1616

@@ -34,5 +34,36 @@ func isPalindrome(s string) bool {
3434
}
3535
return true
3636
}
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+
}
3768
```
3869

05_string/No.392_判断子序列.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020

2121
双指针,逐位判断。如果相同,继续匹配下一位,否则指向 t 的指针右移下一位。
2222

23+
这就是贪心算法。
24+
2325
```go
2426
// date 2023/12/11
2527
func isSubsequence(s string, t string) bool {

0 commit comments

Comments
 (0)