1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution { public String findLongestWord(String s, List<String> dictionary) { dictionary.sort((o1, o2) -> { int diff = Integer.compare(o2.length(), o1.length()); if (diff != 0) { return diff; } return o1.compareTo(o2); });
for (String word : dictionary) { if (match(word, s)) { return word; } }
return ""; }
private boolean match(String word, String s) { if (word.length() > s.length()) { return false; }
int i = 0, j = 0; while (i < word.length()) { while (j < s.length() && word.charAt(i) != s.charAt(j)) { j++; }
if (j == s.length()) { return false; } else { i++; j++; } }
return true; } }
|
References
524. Longest Word in Dictionary through Deleting