LeetCode Reverse String II

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

跟上Reverse Words in a String III.

以上是关于LeetCode Reverse String II的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 151. Reverse Words in a String

*LeetCode--Reverse String II (自己的做法很笨)

leetcode --344. Reverse String

344. Reverse String

Leetcode 557. Reverse Words in a String III

[LeetCode] 344 Reverse String & 541 Reverse String II