faster java solution returning first result, with customized comparator


  • 0
    G
    class Solution {
        public String longestWordG(String[] words) {
            Arrays.sort(words, new MyComparator());
            Set<String> all = new HashSet<>(Arrays.asList(words));
            for(String w : words)
            {
                if(isBuildUp(w, all))
                {
                    return w;
                }
            }
            return "";
        }
        
        private boolean isBuildUp(String w, Set<String> all)
        {
            int l = w.length();
            if( l== 1)
            {
                return true;
            }
            
            String subw = w.substring(0, l - 1);
            boolean isBuildUp = false;
            if(all.contains(subw))
            {
                isBuildUp =  isBuildUp(subw, all);
            }
            if(!isBuildUp)
            {
               all.remove(w); 
            }
            return isBuildUp;
        }
    }
    
    class MyComparator implements Comparator<String> {
    
    	@Override
    	public int compare(String s1, String s2) {
    
            if(s1.length()!=s2.length())
            {
                return s2.length() - s1.length();
            }
    		
            return s1.compareTo(s2);
    	}
    }
    

Log in to reply
 

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