Java simple and fast solution


  • 0
    public class Solution {
        public String findLongestWord(String s, List<String> dictionary) {
            String longest = "";
            for (String word : dictionary) {
                if (word.length() < longest.length() || (word.length() == longest.length() && word.compareTo(longest) > 0)) {
                    continue;
                }
                int i = 0;
                int j = 0;
                while (i < s.length() && j < word.length() && s.length() - i >= word.length() - j) { // last condition short circuit the loop 
                    if (s.charAt(i) == word.charAt(j)) {
                        j++;
                    }
                    i++;
                }
                if (j == word.length()) {
                    longest = word;
                }
            }
            return longest;
        }
    }

Log in to reply
 

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