Reverse String

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 lessthan 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 asoriginal.

 

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]
 1 public class Solution {
 2     public String reverseStr(String s, int k) {
 3         int n = s.length();
 4         StringBuilder result = new StringBuilder();
 5         
 6         for (int i = 0; i < n; ) {
 7             if (i + k > n) {
 8                 // less than k chars left, reverse all
 9                 result.append(reverseStr(s, i, n - 1));
10                 break;
11             } else if (i + k <= n && i + 2 * k > n) {
12                 // k ~ 2k, reverse the first k chars, left the remaining as the same
13                 result.append(reverseStr(s, i, i + k - 1));
14                 result.append(s.substring(i + k));
15                 break;
16             } else if (i + 2 * k <= n) {
17                 // more than 2k chars left, reverse the first k chars
18                 result.append(reverseStr(s, i, i + k - 1));
19                 result.append(s.substring(i + k, i + 2 * k));
20                 i += 2 * k;
21             } 
22         }
23         return result.toString();
24     }
25     
26     private StringBuilder reverseStr(String s, int begin, int end) {
27         StringBuilder result = new StringBuilder();
28         while (end >= begin) {
29             result.append(s.charAt(end--));
30         }
31         return result;
32     }
33 }

 

 

 
posted @ 2017-03-22 05:47  amazingzoe  阅读(128)  评论(0编辑  收藏  举报