您的位置:首页 > 其它

LeetCode 541. Reverse String II (反转字符串 II)

2018-04-08 10:43 351 查看
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

class Solution
{
public String reverseStr(String s, int k)
{
char [] c_arr  = s.toCharArray();

for(int i=0; i<c_arr.length; i=i+2*k)
{
int left = i;
int right = Math.min(i + k - 1, c_arr.length - 1);

while(left < right)
{
// swap char
char temp = c_arr[left];
c_arr[left] = c_arr[right];
c_arr[right] = temp;

left++;
right--;
}

}

return new String(c_arr);
}
}

参考资料:n/a

LeetCode 题目列表 - LeetCode Questions List

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: