代码随想录算法训练营第9天|翻转字符串里的单词、右旋转字符串
lc151翻转字符串里的单词
思路
后序截取单词,顺序添加到结果字符串中
代码
class Solution {
public String reverseWords(String s) {
s = s.trim();
int j = s.length()-1, i = j;
StringBuilder res = new StringBuilder();
while (i >= 0){
while (i >= 0 && s.charAt(i) != ' '){ i--; }
res.append(s.substring(i+1,j+1) + " ");
while (i >= 0 && s.charAt(i) == ' '){ i--; }
j=i;
}
return res.toString().trim();
}
}
卡码网55右旋转字符串
思路
先翻转整个字符串,再局部分别翻转,记得画图哦
代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = Integer.parseInt(in.nextLine());
String s = in.nextLine();
int len = s.length(); //获取字符串长度
char[] chars = s.toCharArray();
reverseString(chars, 0, len - 1); //反转整个字符串
reverseString(chars, 0, n - 1); //反转前一段字符串,此时的字符串首尾尾是0,n - 1
reverseString(chars, n, len - 1); //反转后一段字符串,此时的字符串首尾尾是n,len - 1
System.out.println(chars);
}
public static void reverseString(char[] ch, int start, int end) {
//异或法反转字符串,参照题目 344.反转字符串的解释
while (start < end) {
ch[start] ^= ch[end];
ch[end] ^= ch[start];
ch[start] ^= ch[end];
start++;
end--;
}
}
}
