Skip to content

Commit 04d606b

Browse files
committed
tags
1 parent d758f1e commit 04d606b

File tree

3 files changed

+78
-3
lines changed

3 files changed

+78
-3
lines changed

Leetcode/0001.Two-Sum/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
title: Two Sum
2+
title: 0001.Two Sum
33
tags: Easy
44
author: Kimi Tsai <[email protected]>
55
description:

Leetcode/0438.Find-All-Anagrams-in-a-String/README.md

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
title: Find All Anagrams in a String
2+
title: 0438.Find All Anagrams in a String
33
tags: Medium, Sliding Window
44
author: Kimi Tsai <[email protected]>
55
description:
@@ -47,5 +47,80 @@ s and p consist of lowercase English letters.
4747
https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0438.Find-All-Anagrams-in-a-String/main.go
4848

4949
```go
50+
package findallanagramsinastring
51+
52+
func FindAnagrams(s string, p string) []int {
53+
need, window := make(map[rune]int), make(map[rune]int)
54+
for _, c := range p {
55+
need[c]++
56+
}
57+
58+
left, right := 0, 0
59+
valid := 0
60+
res := []int{} //紀錄結果
61+
for right < len(s) {
62+
c := rune(s[right])
63+
right++
64+
65+
if need[c] > 0 {
66+
window[c]++
67+
if window[c] == need[c] {
68+
valid++
69+
}
70+
}
71+
// fmt.Printf("[%d,%d) \n", left, right)
72+
73+
// 判斷左視窗是否收縮, 看看視窗長度是否同要找的字串的長度
74+
if (right - left) >= len(p) {
75+
if valid == len(need) {
76+
// 想要的字元都找到了, 紀錄index
77+
res = append(res, left)
78+
}
79+
d := rune(s[left])
80+
left++
81+
if need[d] > 0 {
82+
if window[d] == need[d] {
83+
valid--
84+
}
85+
window[d]--
86+
}
87+
}
88+
}
89+
return res
90+
}
91+
92+
// 用 slice 取代 map 來優化
93+
func FindAnagramsSlice(s string, p string) []int {
94+
need := [256]int{}
95+
for _, c := range p {
96+
need[c-'a']++
97+
}
98+
left, right := 0, 0
99+
count := len(p)
100+
res := []int{}
101+
102+
for right < len(s) {
103+
c := s[right] - 'a'
104+
if need[c] > 0 {
105+
count--
106+
}
107+
need[c]--
108+
right++
109+
110+
if count == 0 {
111+
res = append(res, left)
112+
}
113+
114+
if (right - left) >= len(p) {
115+
d := s[left] - 'a'
116+
if need[d] >= 0 {
117+
count++
118+
}
119+
need[d]++
120+
left++
121+
}
122+
}
123+
return res
124+
}
50125

51126
```

Leetcode/0567.Permutation-in-String/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
title: Permutation in String
2+
title: 0567.Permutation in String
33
tags: Medium, Sliding Window
44
author: Kimi Tsai <[email protected]>
55
description:

0 commit comments

Comments
 (0)