首页 > 代码库 > 541. Reverse String II

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]

链接:https://leetcode.com/problems/reverse-string-ii/#/description

4/1/2017

30ms

注意:

1. String如何转为StringBuilder,第6,9行

2. 第6,9行最后要跟s.length()判断而不是s.length()-1

 1 public class Solution {
 2     public String reverseStr(String s, int k) {
 3         StringBuilder sb = new StringBuilder();
 4         for (int i = 0; i < s.length() / k + 1; i++) {
 5             if (i % 2 == 0) {
 6                 StringBuilder st = new StringBuilder(s.substring(i * k, Math.min((i + 1) * k, s.length())));
 7                 sb.append(st.reverse());
 8             } else {
 9                 StringBuilder st = new StringBuilder(s.substring(i * k, Math.min((i + 1) * k, s.length())));
10                 sb.append(st);
11             }
12         }
13         return sb.toString();
14     }
15 }

别人的算法,只用char[]不用stringbuilder

https://discuss.leetcode.com/topic/82626/java-concise-solution

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

更多讨论:

https://discuss.leetcode.com/category/693/reverse-string-ii

 

541. Reverse String II