DAY 8

344. 反转字符串

朴实无华

1
2
3
4
5
6
7
func reverseString(s []byte) {
n := len(s)

for i := 0; i < n/2; i++ {
s[n-i-1], s[i] = s[i], s[n-i-1]
}
}

541.反转字符串 II

朴实无华的递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
func reverseStr(s string, k int) string {
n := len(s)
if n <= k {
return reverse(s)
} else if n > k && n < 2*k {
return reverse(s[:k]) + s[k:]
} else {
return reverse(s[:k]) + s[k:2*k] + reverseStr(s[2*k:], k)
}

}

func reverse(s string) string {
bytes := []byte(s)
n := len(bytes)
for i := 0; i < n/2; i++ {
bytes[i], bytes[n-i-1] = bytes[n-i-1], bytes[i]
}
return string(bytes)
}

LCR 122.路径加密

朴实无华

1
2
3
4
5
6
7
8
9
10
11
func pathEncryption(path string) string {
ans := ""
for _, c := range path {
if c == '.' {
ans += " "
} else {
ans += string(c)
}
}
return ans
}

151.反转字符串中的单词

Go 写起来真舒服

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func reverseWords(s string) string {
for s[0] == ' ' {
s = s[1:]
}
n := len(s)
ans := ""

for i := 0; i < n; i++ {
word := ""
for i < n && s[i] != ' ' {
word += string(s[i])
i++
}
ans = " " + word + ans

for i+1 < n && s[i+1] == ' ' {
i++
}
}
return ans[1:]
}

LCR 182.动态口令

???

1
2
3
func dynamicPassword(password string, target int) string {
return password[target:] + password[:target]
}

DAY 9

28.找出字符串中第一个匹配项的下标

简单复习了一下 KMP,但你要我写我肯定写不出来

这东西写法太多而且感觉有点乱

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
func strStr(haystack string, needle string) int {
n, m := len(haystack), len(needle)
i, j := 0, 0
next := getNext(needle)
for i < n {
if j == -1 || haystack[i] == needle[j] {
i++
j++
} else {
j = next[j]
}
if j == m {
j = next[j]
return i - m
}
}
return -1
}

func getNext(s string) []int {
n := len(s)
next := make([]int, n+1)
i, j := 0, -1
next[0] = -1
for i < n {
if j == -1 || s[i] == s[j] {
i++
j++
next[i] = j
} else {
j = next[j]
}
}
return next
}

459. 重复的子字符串

真的是非常巧妙的算法

1
2
3
func repeatedSubstringPattern(s string) bool {
return strings.Contains(s[1:]+s[:len(s)-1], s)
}