当前位置:网站首页>Leetcode- reverse string ii- simple

Leetcode- reverse string ii- simple

2022-06-13 05:49:00 AnWenRen

title :541 Reverse string - Simple

subject

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 .

Example 1

 Input :s = "abcdefg", k = 2
 Output :"bacdfeg"

Example 2

 Input :s = "abcd", k = 2
 Output :"bacd"

Tips

  • 1 <= s.length <= 104
  • s It consists of lowercase English only
  • 1 <= k <= 104

Code Java

		public String reverseStr(String s, int k) {
    
        StringBuilder sb = new StringBuilder();
        int count = 0; //  Record the start position of the reversal 
        for (int i = 0, j = 1, g = 1; i < s.length(); i++) {
    
            if (i < k * j) {
    
                sb.insert(count, s.charAt(i));
            } else if (i < k * g * 2) {
    
                sb.append(s.charAt(i));
            } else {
    
                j += 2;
                g ++;
                count = i;
                i--;
            }
        }
        return sb.toString();
    }
原网站

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