题解 | #单词倒排#
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
import java.util.*;
import java.lang.*;
/**
难点:
while(i>=0 && Character.isLetter(c)){
i--;
c = str.charAt(i);
}
res.append(str.substring(i+1,j+1)+" ");
这样写会出现越界错误,因为当i=0时,i--会变成-1,str.charAt(-1)会报错。所以不如直接去掉c
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
StringBuilder res = new StringBuilder();
int n = str.length();
int i = n - 1;
int j = n - 1;
while (i >= 0) {
while (i >= 0 && Character.isLetter(str.charAt(i))) {
i--;
}
res.append(str.substring(i + 1, j + 1) + " ");
while (i >= 0 && !Character.isLetter(str.charAt(i))) {
i--;
}
j = i;
}
System.out.println(res.toString().trim());
}
}

