题解 | #单词倒排#
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
思路: 先把字母取出来,把中间非字母变成空格也取出来,然后split,倒序输出
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str=in.nextLine();
String temp="";
boolean isKong=true;//先为true,把开头可能的空格干掉
for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
if((ch>=65 && ch<=90) || (ch>=97 && ch<=122)){
temp+=ch;//是字母就取
isKong=false;//设false是为了下一个不是字母的时候去取空格
}else{
if(!isKong){
temp+=" ";
isKong=true;//设true是为了上一个是空格的时候直到下一个字母都不取
}
}
}
if(temp.substring(temp.length()-1)==" "){//判断最后一个字符是否是空格
temp=temp.substring(0,temp.length()-2);//是就干掉
}
String[] res=temp.split(" ");//按空格做数组
for(int i=res.length-1;i>=0;i--){//倒序输出
System.out.print(res[i]+" ");
}
//其实可以不管空格问题,不是字母一律取空格,最后倒序输出的时候再判断是空字符串就continue应该也是可以的
}
}