题解 | #单词倒排#
单词倒排
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);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str = in.nextLine();
// System.out.println(str);
ArrayList<String> list = getStrArr(str);
// System.out.println(list);
int n = list.size();
for(int i = n-1;i>-1;i--){
if(i==0){
System.out.print(list.get(i));
} else {
System.out.print(list.get(i)+" ");
}
}
}
}
public static ArrayList<String> getStrArr(String input) {
ArrayList<String> wordList = new ArrayList<String>();
int n = input.length();
String tempStr = "";
for (int i = 0; i < n; i++) {
char tempChar = input.charAt(i);
// System.out.println(tempChar);
if ((tempChar >= 'A' && tempChar <= 'Z') || (tempChar >= 'a' &&
tempChar <= 'z')) {
tempStr = tempStr + tempChar;
if (i == n - 1) {
wordList.add(tempStr);
}
} else {
if (!tempStr.equals("")) {
wordList.add(tempStr);
// System.out.println(tempStr);
tempStr = "";
continue;
} else {
continue;
}
}
}
return wordList;
}
}
查看9道真题和解析