一、[151]翻转字符串里的单词
重点:见注释
java
class Solution {
public String reverseWords(String s) {
//1、移除多余的空格
StringBuilder stringBuilder = removeSpace(s);
//2、反转整个字符串
reverse(stringBuilder,0,stringBuilder.length()-1);
//3、反转每个单词
reverseEachWord(stringBuilder);
return stringBuilder.toString();
}
StringBuilder removeSpace(String s){
StringBuilder stringBuilder=new StringBuilder();
int left=0,right=s.length()-1;
while(s.charAt(left)==' '){
left++;
}
while(s.charAt(right)==' '){
right--;
}
for(int i=left;i<right+1;i++){
if(s.charAt(i)!=' '){
stringBuilder.append(s.charAt(i));
}else if(stringBuilder.charAt(stringBuilder.length()-1)!=' '){
//若结束位置不为空格,则加个空格,否则什么也不做
stringBuilder.append(s.charAt(i));
}
}
return stringBuilder;
}
//设置开始结束的标记
void reverse(StringBuilder stringBuilder,int left,int right){
while(left<right){
char tmp = stringBuilder.charAt(left);
//设置值setCharAt
stringBuilder.setCharAt(left,stringBuilder.charAt(right));
stringBuilder.setCharAt(right,tmp);
left++;
right--;
}
}
//注意一下
void reverseEachWord(StringBuilder stringBuilder){
int left=0,right=1;
int n=stringBuilder.length();
while(left<n){
while(right<n&&stringBuilder.charAt(right)!=' '){
right++;
}
reverse(stringBuilder,left,right-1);
left=right+1;
right=left+1;
}
}
}
二、[卡码网55]右旋转字符串
重点:技巧
反转三次
java
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();
reverse(chars,0,len-1);
reverse(chars,0,n-1);
reverse(chars,n,len-1);
System.out.println(chars);
}
public static void reverse(char[] ch,int start,int end){
while(start<end){
char tmp=ch[start];
ch[start]=ch[end];
ch[end]=tmp;
start++;
end--;
}
}
}