344.反转字符串
func reverseString(s []byte) {
l, r := 0, len(s) - 1
for l < r {
s[l], s[r] = s[r], s[l]
l++
r--
}
return
}
541.反转字符串II
func reverseStr(s string, k int) string {
n := len(s)
ss := []byte(s)
for i := 0; i < n; i += 2 * k {
reverse(ss, i, min(i + k, n) - 1)
}
return string(ss)
}
func reverse(s []byte, l, r int) {
for l < r {
s[l], s[r] = s[r], s[l]
l++
r--
}
return
}
卡码网:54.替换数字
正则表达式替换
package main
import (
"fmt"
"regexp"
)
func main() {
var str string
fmt.Scanln(&str)
re := regexp.MustCompile(`\d+`)
newStr := re.ReplaceAllString(str, "number")
fmt.Printf("%s", newStr)
}
151.反转字符串中的单词
func reverseWords(s string) string {
str := []byte(s)
str = trim(str)
reverse(str)
l, r, n := 0, 0, len(str)
for l < n {
for r < n && str[r] != ' ' {
r++
}
reverse(str[l:r])
l = r + 1
r = r + 1
}
return string(str)
}
func reverse(s []byte) {
l, r := 0, len(s)-1
for l < r {
s[l], s[r] = s[r], s[l]
l++
r--
}
return
}
func trim(s []byte) []byte {
l, r := 0, len(s)-1
newstr := []byte{}
for s[l] == ' ' {
l++
}
for s[r] == ' ' {
r--
}
for l <= r {
if s[l] != ' ' || (s[l] == ' ' && newstr[len(newstr)-1] != ' ') {
newstr = append(newstr, s[l])
l++
} else {
l++
}
}
return newstr
}
卡码网:55.右旋转字符串
package main
import "fmt"
func main() {
var s string
var n int
fmt.Scanln(&n)
fmt.Scanln(&s)
ss := []byte(s)
reverseString(ss, n)
fmt.Printf(string(ss))
}
func reverseString(s []byte, n int) {
reverse(s)
reverse(s[:n])
reverse(s[n:])
}
func reverse(s []byte) {
l, r := 0, len(s)-1
for l < r {
s[l], s[r] = s[r], s[l]
l++
r--
}
}
总结
go语言基础知识欠缺,学习常用库函数