一、151.翻转字符串里的单词
题目链接:https://leetcode.cn/problems/reverse-words-in-a-string/
文章讲解:https://programmercarl.com/0151.%E7%BF%BB%E8%BD%AC%E5%AD%97%E7%AC%A6%E4%B8%B2%E9%87%8C%E7%9A%84%E5%8D%95%E8%AF%8D.html#%E7%AE%97%E6%B3%95%E5%85%AC%E5%BC%80%E8%AF%BE
视频讲解:https://www.bilibili.com/video/BV1uT41177fX
1.1 初见思路
1.先翻转每个单词,再翻转整个字符串
2.消除多余空格
1.2 具体实现
class Solution {
public String reverseWords(String s) {
//1.把字符串去掉多余空格
StringBuilder stringBuilder = removeMoreSpace(s);
//2.翻转整个字符串
reverseWholeStr(stringBuilder);
//3.翻转每个单词
reverAllWord(stringBuilder);
return stringBuilder.toString();
}
public StringBuilder removeMoreSpace(String s){
StringBuilder stringBuilder = new StringBuilder();
int left =0;
int right = s.length()-1;
while(s.charAt(left)==' '){
left++;
}
while(s.charAt(right)==' '){
right--;
}
for(int i=left;i<=right;i++){
//如果是空格,则跳过,得保留一个空格的
if(s.charAt(i)==' '){
if(s.charAt(i-1)!=' '){
stringBuilder.append(' ');
}
continue;
}
// System.out.println("i="+i+"::::对应的s"+s.charAt(i));
stringBuilder.append(s.charAt(i));
}
return stringBuilder;
}
public void reversePartStr(StringBuilder sb,int left ,int right){
while(left<right){
char temp = sb.charAt(right);
sb.setCharAt(right,sb.charAt(left));
sb.setCharAt(left,temp);
left++;
right--;
}
}
public void reverseWholeStr(StringBuilder stringBuilder){
reversePartStr(stringBuilder, 0, stringBuilder.length() - 1);
System.out.println(stringBuilder);
}
public void reverAllWord(StringBuilder sb){
int start = 0;
int end = 1;
int n = sb.length();
while (start < n) {
while (end < n && sb.charAt(end) != ' ') {
end++;
}
reversePartStr(sb, start, end - 1);
start = end + 1;
end = start + 1;
}
}
}
1.3 重难点
二、 右旋字符串
题目链接:https://kamacoder.com/problempage.php?pid=1065
文章讲解:https://programmercarl.com/kamacoder/0055.%E5%8F%B3%E6%97%8B%E5%AD%97%E7%AC%A6%E4%B8%B2.html#%E5%85%B6%E4%BB%96%E8%AF%AD%E8%A8%80%E7%89%88%E6%9C%AC
视频讲解:https://www.bilibili.com/video/BV12A4y1Z7LP
2.1 初见思路
1.翻转整个字符串
2.反转前一段字符串
3.反转后一段字符串
2.2 具体实现
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--;
}
}
}