**leetcode:**https://leetcode.com/problems/reverse-string-ii
Description:
Given a string s
and an integer k
, reverse the first k
characters for every 2k
characters counting from the start of the string.
If there are fewer 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 leave the other as original.
Idea:
Step1: because the problem need to change the range between k character and 2k characters, we traverse the string and increase the index by 2k
Step2: if left characters less than k characters, it means the current index + k will larger than the length of string, so reverse the whole left string
Step3: if there are less than 2k
but greater than or equal to k
characters, then reverse the first k
characters. it menas if the current index plus k won’t exceed the length of string, just reverse the first k character. the range of the reverse is(i, i+k-1)
Code:
class Solution {
public String reverseStr(String s, int k) {
int length = s.length()-1;
char[] result = s.toCharArray();
// traverse the string and set the index increased by 2k each time
for(int i=0; i<=length; i = i+2*k){
// if the left characters more than k characters(so the current index + k, it will less or equal than length of string), reverse first k
if (i+k<=length){
reverse(result, i, i+k-1);
continue;
}
// if left characters less than k characters, reverse all
if(i+k > length){
reverse(result, i, length);
continue;
}
}
return new String(result);
}
public void reverse(char[]s, int i, int j){
while(i<j){
char temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
}
}
return the character array to string
new String(character);