func reverseString(s []byte) {
length := len(s)
left, right := 0, length-1
for left <= right {
s[left], s[right] = s[right], s[left]
left++
right--
}
return
}
func reverseStr(s string, k int) string {
arr := []byte(s)
length := len(arr)
left := 0
for left < length {
// 剩余字符少于 k 个,则将剩余字符全部反转。
if (length-left) < k {
reverse(arr, left, length-1)
} else {
reverse(arr, left, left+k-1)
}
left = left+k*2
}
return string(arr)
}
func reverse(s []byte, left int, right int) {
if left >= right {
return
}
for left<=right {
s[left], s[right] = s[right], s[left]
left++
right--
}
}
func reverseOnlyLetters(s string) string {
arr := []byte(s)
length := len(arr)
left, right := 0, length-1
for left <= right {
for left <= right && notA2z(arr[left]) {
left++
}
for left <= right && notA2z(arr[right]) {
right--
}
if left <= right {
arr[left], arr[right] = arr[right], arr[left]
left++
right--
}
}
return string(arr)
}
func notA2z (ch byte) bool {
// 大写字母 A - Z 的 ASCII 码范围为 [65,90]
// 小写字母 a - z 的 ASCII 码范围为 [97,122]
if ch < 65 || ch > 122 {
return true
}
if ch > 90 && ch < 97 {
return true
}
return false
}
func reverseWords(s string) string {
arr := []byte(s)
length := len(arr)
left, right := 0, length-1
// 去除首尾空格
for {
if arr[left] == ' ' {
left++
} else {
break
}
}
for {
if arr[right] == ' ' {
right--
} else {
break
}
}
var arr2 []byte
if right < length-1 {
arr2 = arr[left:right+1]
} else {
arr2 = arr[left:]
}
length = len(arr2)
reverse(arr2, 0, length-1)
var arr3 []byte
left = 0
for left < length {
for left < length {
if arr2[left] == ' ' {
left++
} else {
break
}
}
right = left
for right < length {
if arr2[right] == ' ' {
break
} else {
right++
}
}
reverse(arr2, left, right-1)
arr3 = append(arr3, arr2[left:right]...)
if right == length {
break
}
arr3 = append(arr3, ' ')
left = right
}
return string(arr3)
}
func reverse(arr []byte, left int, right int) {
if left >= right {
return
}
for left <= right {
arr[left], arr[right] = arr[right], arr[left]
left++
right--
}
}
func isPalindrome(s string) bool {
arr := []rune{}
for _, v := range s {
if res, ch := isValid(v); res {
arr = append(arr, ch)
}
}
length := len(arr)
left, right := 0, length-1
for left<=right {
if arr[left] != arr[right] {
return false
}
left++
right--
}
return true
}
func isValid(ch rune) (bool, rune) {
if ch >= 'A' && ch <= 'Z' {
ch = ch | 32
return true, ch
}
if ch >= 'a' && ch <= 'z' {
return true, ch
}
if ch >= '0' && ch <= '9' {
return true, ch
}
return false, ch
}
题目链接:LeetCode-387. 字符串中的第一个唯一字符
func firstUniqChar(s string) int {
maps := make(map[rune]int, 0)
for _, v := range s {
maps[v]++
}
for i, v := range s {
if maps[v] == 1 {
return i
}
}
return -1
}
func isAnagram(s string, t string) bool {
if len(s) != len(t) {
return false
}
maps := getMap(s)
for _, v := range t {
maps[v]--
if maps[v] < 0 {
return false
}
}
return true
}
func getMap(s string) map[rune]int {
ret := make(map[rune]int, 0)
for _, v := range s {
ret[v]++
}
return ret
}