10 ms, java, 100% beat


  • 0
    Y
    public String findLongestWord(String s, List<String> d) {
            String longestWord = "";
            for (String element : d) {
                if (isSubString(s, element)) {
                    if (element.length() > longestWord.length()) {
                        longestWord = element;    
                    }
                    else if (element.length() == longestWord.length() && 
                            element.compareTo(longestWord) < 0) {
                        longestWord = element;
                    }
                }
            }
            return longestWord;
        }
        
        // search d in s
        private boolean isSubString(String s, String d) {
            if (d.length() > s.length())    return false;
            if (d.length() == s.length())   return s.equals(d);
            
            int lo = 0;
            for (int i = 0; i < d.length(); ++i) {
                // there is not enough character in s
                if (s.length() - lo < d.length() - i)   return false;
                
                lo = s.indexOf(d.charAt(i), lo);
                if (-1 == lo)   return false;
                ++lo;
                
            }
            return true;
        }
    
    
    

Log in to reply
 

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