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"
- The string consists of lower English letters only.
- Length of the given string and k will in the range [1, 10000]
思考方式
- 把字串用 2k 個分成一組,前面 k 個反轉,後面不動
Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public String reverseStr(String s, int k) { | |
char[] input = s.toCharArray(); | |
int i, j; | |
char tmp; | |
for(int start = 0; start < input.length; start += 2 * k) { | |
i = start; | |
j = Math.min(start + k - 1, input.length - 1); | |
while(i < j) { | |
tmp = input[i]; | |
input[i++] = input[j]; | |
input[j--] = tmp; | |
} | |
} | |
return new String(input); | |
} | |
} |
沒有留言:
張貼留言