题解 | #单词倒排#
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836?tpId=37&tqId=38366&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
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.hasNext()) { // 注意 while 处理多个 case
String str = in.nextLine();
ArrayList<String> list = new ArrayList<String>();
String tempStr = "", tempChar;
for (int i = 0; i < str.length(); i++) {
tempChar = str.charAt(i) + ""; //每次获取当前下标字符
if ( tempChar.matches("[a-zA-Z]") ) { //是字母则开始构建单词
tempStr += tempChar;
} else if (!tempChar.matches("[a-zA-Z]") && tempStr != "") {
//当前字符不是字母 且 构建单词tempStr不为空,停止构建单词,把已构建单词放入list。 并且初始化tempStr
list.add(tempStr);
tempStr = "";
}
if (i == str.length() - 1 &&
tempStr != "") { //到达最后一个字符 搽屁股
list.add(tempStr);
tempStr = "";
}
}
//System.out.println(str.charAt(str.length()-1));
//System.out.println(list);
for (int i = list.size() - 1; i >= 0; i--) {
System.out.print(list.get(i) + " ");
}
}
}
}