344. 反转字符串 - 力扣(LeetCode)
class Solution {
public void reverseString(char[] s) {
int left = 0;
int right = s.length-1;
while(left < right){
char tmp = s[left];
s[left] = s[right];
s[right] = tmp;
left++;
right--;
}
}
}
541. 反转字符串 II - 力扣(LeetCode)
class Solution {
public static String reverseStr(String s, int k) {
char[] chars = s.toCharArray();
//反转的时候维持左闭右开的区间
int length = s.length();
//每次步进2K
for(int i=0;i<length;i+=2*k){
// if(i+2*k<=length){
// reverse(chars,i,i+k);
// }else if(i+2*k > s.length() && i+k <= s.length()){
// reverse(chars,i,i+k);
// }else{
// reverse(chars,i,length);
// }
if(i+k>length){
reverse(chars,i,length);
}else{
reverse(chars,i,i+k);
}
}
return new String(chars);
}
/**
* 翻转chars,包含了起始位置start和结束位置end
* @param chars
* @param start
* @param end
*/
private static void reverse(char[] chars,int start,int end){
int i=start;
int j=end-1;
while (i<j){
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
i++;
j--;
}
}
}
151. 反转字符串中的单词 - 力扣(LeetCode)
class Solution {
public static String reverseWords(String s) {
char[] chars = trimByRule(s.toCharArray());
reverse(chars,0,chars.length);
int start = 0;
for(int i=0;i<chars.length;i++){
if (chars[i] == ' '){
reverse(chars,start,i);
start = i+1;
}
}
reverse(chars,start, chars.length);
return new String(chars);
}
private static char[] trimByRule(char[] chars){
char[] tmp = new char[chars.length];
Arrays.fill(tmp,' ');
int i = 0;
int j = 0;
while (j < chars.length) {
while (chars[j] != ' ' || (j > 0 && chars[j - 1] != ' ')) {
tmp[i++] = chars[j++];
if(j>=chars.length){
break;
}
}
while (j<chars.length && chars[j] == ' '){
j++;
if(j>=chars.length){
break;
}
}
}
j=tmp.length-1;
while (tmp[j] == ' '){
j--;
}
char[] result = new char[j+1];
for(i=0;i<=j;i++){
result[i] = tmp[i];
}
return result;
}
/**
* 翻转chars,包含了起始位置start和结束位置end
* @param chars
* @param start
* @param end
*/
private static void reverse(char[] chars,int start,int end){
int i=start;
int j=end-1;
while (i<j){
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
i++;
j--;
}
}
}