题解 | #单词倒排#

单词倒排

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(" "));
    }
}

全部评论

相关推荐

06-02 15:53
阳光学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务