题解 | #单词倒排#
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
import java.util.*;
public class Main {
public Main() {
}
public String reverse(String str) {
// 匹配非字母的字符进行分割
String[] words = str.split("[^A-Za-z]");
StringBuilder result = new StringBuilder();
// 逆序添加分割完的单词
for (int i = words.length - 1; i >= 0; i--) {
result.append(words[i]).append(" ");
}
return result.toString().trim();
}
public static void main(String[] args) {
Main solution = new Main();
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String str = in.nextLine();
String res = solution.reverse(str);
System.out.println(res);
}
}
}
public class Main {
public Main() {
}
public String reverse(String str) {
// 匹配非字母的字符进行分割
String[] words = str.split("[^A-Za-z]");
StringBuilder result = new StringBuilder();
// 逆序添加分割完的单词
for (int i = words.length - 1; i >= 0; i--) {
result.append(words[i]).append(" ");
}
return result.toString().trim();
}
public static void main(String[] args) {
Main solution = new Main();
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String str = in.nextLine();
String res = solution.reverse(str);
System.out.println(res);
}
}
}