Force link :
https://leetcode-cn.com/probl...
Their thinking :
- Given a string s And an integer k, From the beginning of the string , Each count to 2k Characters , Just reverse this 2k The first... In the character k Characters . If the remaining characters are less than k individual , Reverse all remaining characters . If the remaining characters are less than 2k But greater than or equal to k individual , Before reversal k Characters , The rest of the characters remain the same .
- This problem is actually a reduction problem , There are two conditions in the solution :(1) Per count 2k Characters , Then it meets the conditions , Judge (2) There are two conditions for judgment : If the distance character ends >=k Characters , So before turning k Characters , If <k, Then flip the remaining characters
func reverseStr(s string, k int) string {
n := len(s)
bs := []byte(s)
for i := 0; i < n; i += (2 * k) {
if i + k <= n {
reverse(bs[i:i+k])
} else {
reverse(bs[i:n])
}
}
return string(bs)
}
func reverse(s []byte) {
n := len(s)
low, high := 0, n-1
for low <= high {
s[low], s[high] = s[high], s[low]
low++
high--
}
}







