0
点赞
收藏
分享

微信扫一扫

【词典中最长的单词(720-java)】

雷亚荣 2022-01-15 阅读 57

词典中最长的单词(720-java)

public class LC242_720_longestWord {
    //排序
    public static String longestWord(String[] words) {
        //1.放到set
        Set<String> set = new HashSet<>();
        for (String word : words) {
            set.add(word);
        }
        //2.排序
        Arrays.sort(words, (a, b) -> a.length() == b.length()
                ? a.compareTo(b) : b.length() - a.length());
        //3.校验
        for (String word : words) {
            boolean flag = true;
            for (int i = 1; i < word.length(); i++) {
                if (!set.contains(word.substring(0, i))) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                return word;
            }
        }
        return "";
    }
    public static void main(String[] args) {
        System.out.println(longestWord(new String[]{"w", "wo", "wor", "worl", "world"}));
    }
}
举报

相关推荐

0 条评论