题解 | 单词倒排
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String line = in.nextLine();
int length = line.length();
ArrayList<String> list = new ArrayList<>();
int startIndex = 0, endIndex = 0;
for (int i = 0; i < length; i++) {
char ch = line.charAt(i);
if (ch >= 'A' && ch <= 'z' && i != length - 1) { // 保证是英文字母
endIndex = i + 1;
} else { // 不是英文字母
if (i == length - 1) endIndex++; // 防止跳过最后一个单词
if (endIndex > startIndex) list.add(line.substring(startIndex, endIndex));
startIndex = ++endIndex; // 先运算再赋值
}
}
StringBuilder sb = new StringBuilder();
for (int i = list.size(); i > 0; i--) { // 倒序显示
sb.append(list.get(i - 1)).append(" ");
}
sb.setLength(sb.length() - 1); // 去除最后一个空格
System.out.println(sb.toString());
}
}
