题解 | 单词倒排
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
import java.util.Scanner; // 注意类名必须为 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 a = in.nextLine(); //先循环遍历,将特殊字符一律替换为空白符,方便后面分割数组 StringBuffer sf1 = new StringBuffer(a); for(int i=0;i<sf1.length();i++){ if(!Character.isLetter(sf1.charAt(i))){ sf1.setCharAt(i,' '); } } /** 如果熟悉正则匹配表达式,可以不用上面的方法,直接用正则模式 "[^A-Za-z]"。其中^如果在[]字符集中,表示取反,不是大写字母、小写字母的字符 // String[] str = str.split("[^A-Za-z]"); */ String[] str = sf1.toString().split(" "); StringBuffer sf = new StringBuffer(); for(int i = str.length-1; i >= 0; i--){ if(i==0){ sf.append(str[i]); } else{ sf.append(str[i]).append(" "); } } System.out.print(sf); } } }