541. Reverse String II - Easy

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

 

Example:

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

 

Restrictions:

  1. The string consists of lower English letters only.
  2. Length of the given string and k will in the range [1, 10000]

 

time: O(n), space: O(1)

class Solution {
    public String reverseStr(String s, int k) {
        if(s.length() < 2) {
            return s;
        }
        char[] chs = s.toCharArray();
        for(int i = 0; i < chs.length; i += 2 * k) {
            reverse(chs, i, Math.min(i + k - 1, chs.length - 1));
        }
        return new String(chs);
    }
    
    private void reverse(char[] s, int i, int j) {
        while(i < j) {
            char tmp = s[i];
            s[i] = s[j];
            s[j] = tmp;
            
            i++;
            j--;
        }
    }
}

 

posted @ 2019-08-11 15:09  fatttcat  阅读(78)  评论(0编辑  收藏  举报