首页 > 代码库 > LeetCode Reverse String II

LeetCode Reverse String II

原题链接在这里:https://leetcode.com/problems/reverse-string-ii/#/description

题目:

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] 

题解:

是Reverse String的进阶题目.

每2k个char中前k个char swap.

Time Complexity: O(n), n = s.length(). Space: O(n).

AC Java:

 1 public class Solution {
 2     public String reverseStr(String s, int k) {
 3         int len = s.length();
 4         char [] charArr = s.toCharArray();
 5         int i = 0;
 6         while(i < len){
 7             int j = Math.min(i+k-1, len-1);
 8             swap(charArr, i, j);
 9             i += 2*k;
10         }
11         
12         return new String(charArr);
13     }
14     
15     private void swap(char [] s, int i, int j){
16         while(i<j){
17             char temp = s[i];
18             s[i] = s[j];
19             s[j] = temp;
20             i++;
21             j--;
22         }
23     }
24 }

 

LeetCode Reverse String II