541. Reverse String II

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]

题目含义:给定一个字符串和一个整数k,你需要反转从字符串开始计数的每2k个字符的前k个字符。如果剩余少于k个字符,则将所有字符都反转。如果小于2k但大于或等于k个字符,则反转前k个字符,并将另一个作为原始字符

 1    private void swapStr(char[] arr, int l, int r) {
 2         while (l < r) {
 3             char temp = arr[l];
 4             arr[l++] = arr[r];
 5             arr[r--] = temp;
 6         }
 7     }
 8     
 9     public String reverseStr(String s, int k) {
10         char[] arr = s.toCharArray();
11         int n = arr.length;
12         int i = 0;
13         while (i < n) {
14             int j = Math.min(i + k - 1, n - 1);
15             swapStr(arr, i, j);
16             i += 2 * k;
17         }
18         return String.valueOf(arr);        
19     }

 

posted @ 2017-10-17 10:40  daniel456  阅读(106)  评论(0编辑  收藏  举报