LeetCode 541. Reverse String II (反转字符串 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]

 


题目标签:String

 

  今天登陆突然发现LeetCode 有中文版本了- -,再也不用纠结于 如何翻译题目名字了。
 
  题目给了我们一个string s 和 int k,让我们每次在2k 个 chars 里只反转 k 个chars。
  利用Reverse String 里的 two pointers 来反转k 个chars,每一次增加 i by 2*k 就可以了。
  具体请看code。
 
 
 

Java Solution:

Runtime beats 67.31% 

完成日期:04/07/2018

关键词:two pointers

关键点:swap left and right chars

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

参考资料:n/a

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2018-04-08 10:43  Jimmy_Cheng  阅读(309)  评论(0编辑  收藏  举报