Simple Java Code using TreeSet


  • 0
    S
    public String longestWord(String[] words) {
            Set<String>[] map = new Set[31];
            String ans = "";
    // put the words in bucket of HashSet
            for(String s : words){
                if(map[s.length()] == null)
                    map[s.length()] = new TreeSet<String>();
                map[s.length()].add(s);
            }
    //Go through each word in the bucket from the end
            for(int i = 30; i > 0; i--){
                if(map[i] != null){
                    for(String candidate : map[i]){
                        for(int j = candidate.length() - 1; j > 0; j--){
                            String temp = candidate.substring(0,j); 
                            if(map[temp.length()] == null || !map[temp.length()].contains(temp)) // if the substring is not present in the dictionary then break else continue
                                break;
                            if(j == 1) 
                                return candidate; // return the candidate
                        }
                    }
                }
            }
            return map[1] != null ? ((TreeSet<String>) map[1]).first() : ans;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.