题解 | #单词倒排#
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //空格划分输入,保存到数组中 List<String> list = new ArrayList<>(); while (sc.hasNext()) { String str = sc.next(); //next()遇到空格或者回车就停止 if(!have2(str)){ list.add(str); }else{ String[] arr = split2(str); for(int j=0; j<arr.length; j++){ list.add(arr[j]); } } } StringBuilder sb = new StringBuilder(); Collections.reverse(list); for(String sss: list){ sb.append(sss).append(" "); } System.out.println(sb.toString()); } public static String[] split2(String s){ char[] chars = s.toCharArray(); char temp = ' '; for (int i=0; i<chars.length; i++) { char c = chars[i]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { continue; } else { //c是特殊字符==>间隔符 s = s.replace(c, temp); //.replace(char oldChar, char newChar),特别注意要赋值 } } return s.split(String.valueOf(temp)); } public static boolean have2(String s){ char[] chars = s.toCharArray(); for (char c : chars) { if (c<'a' || c>'z' || c<'A' || c>'Z') { return true; } } return false; } }