congr / world

2 stars 1 forks source link

LeetCode : 720. Longest Word in Dictionary #472

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/longest-word-in-dictionary/

image

congr commented 5 years ago
class Solution {
    public String longestWord(String[] words) {
        Arrays.sort(words);
        Set<String> set = new HashSet();

        String longest = "";
        for (String w : words) {
            String p = w.substring(0, w.length()-1);
            if (w.length() == 1 || set.contains(p)) {
                set.add(w);
                if (longest.length() < w.length()) longest = w;
            }
        }

        return longest;        
    }
}