给定单词倒排
实现代码:
public static void main(String[] args) {Scanner scanner = new Scanner(System.in);// 输入的字符串String input = scanner.nextLine();// 存储单词List<String> words = new ArrayList<>();// 存储当前单词StringBuilder currentWord = new StringBuilder();// 遍历字符串for (char c : input.toCharArray()) {// 如果是字母,则添加到当前单词中if (Character.isLetter(c)) {currentWord.append(c);} else {// 遇到非字母时,将当前单词添加到列表中,并清空当前单词if (currentWord.length() > 0) {words.add(currentWord.toString());currentWord.setLength(0);}}}// 添加最后一个单词if (currentWord.length() > 0) {words.add(currentWord.toString());}// 倒序List<String> reversedWords = new ArrayList<>();for (int i = words.size() - 1; i >= 0; i--) {reversedWords.add(words.get(i));}// 将单词列表转换为字符串String result = String.join(" ", reversedWords);System.out.println(result);}