题解 | #单词倒排#
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
import java.util.Scanner; import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { /** * 单词列表 */ public static final List<String> WORD_LIST = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"); /*** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); System.out.println(get(str)); } private static String get(String str) { LinkedList<String> list = new LinkedList<>(); // 遍历时,上一个非字母的位置 int cursor = 0; // 遍历输入的单词,把是字母的单词都搂出来放到list里面 for (int i = 0, len = str.length(); i < len; i++) { if( !WORD_LIST.contains(str.charAt(i) + "")){ String substring = str.substring(cursor, i); if (substring.length() > 0) { list.add(substring); } cursor = i + 1; } } // 如果是单词结尾,还要把他加上,如果是其他符号结尾,那什么也搂不到 String substring = str.substring(cursor); if (substring.length() > 0) { list.add(substring); } // 翻转列表 Collections.reverse(list); // 输出字符串 return list.stream().collect(Collectors.joining(" ")); } }