问题:
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:
- The string consists of lower English letters only.
- Length of the given string and k will in the range [1, 10000]
解决:
【题目要求】每隔k隔字符,翻转k个字符,最后如果不够k个了的话,剩几个就翻转几个。
① 直接的方法就是先用n/k算出来原字符串s能分成几个长度为k的字符串,然后开始遍历这些字符串,遇到2的倍数就翻转,翻转的时候注意考虑下是否已经到s末尾了。
public class Solution {//10ms
public String reverseStr(String s, int k) {
char[] schar = s.toCharArray();
int count = s.length() / k;//字符串可以被分为多少段
for (int i = 0;i <= count ;i ++ ) {
if(i % 2 == 0){
if(i * k + k < s.length()){//确保有k个值
reverse(schar,i * k,i * k + k - 1);
}else{//最后不够k个数
reverse(schar,i * k,s.length() - 1);
}
}
}
return new String(schar);
}
public void reverse(char[] schar,int start,int end){
while(start <= end){
char tmp = schar[start];
schar[start] = schar[end];
schar[end] = tmp;
start ++;
end --;
}
}
}
② 这种方法更好理解 一点。
public class Solution {//7ms
public String reverseStr(String s, int k) {
int len = s.length();
char schar[] = s.toCharArray();
int i = 0;
while (i < len){
int j = Math.min(i+k-1,len-1);
reverse(schar,i,j);
i += 2 * k;
}
return String.valueOf(schar);
}
public void reverse(char[] schar,int start,int end){
while(start <= end){
char tmp = schar[start];
schar[start] = schar[end];
schar[end] = tmp;
start ++;
end --;
}
}
}