当前位置:网站首页>Leetcode topic [string]-541- reverse string II

Leetcode topic [string]-541- reverse string II

2022-06-12 18:34:00 LabRat

Force link :
https://leetcode-cn.com/probl...
Their thinking :

  1. 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 .
  2. 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--
    }    
}
原网站

版权声明
本文为[LabRat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202281554515888.html