[LeetCode] Problem 524 - Longest Word in Dictionary through Deleting

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

Example

No.1

Input:
s = “abpcplea”, d = [“ale”,”apple”,”monkey”,”plea”]

Output:
“apple”

No.2

Input:
s = “abpcplea”, d = [“a”,”b”,”c”]

Output:
“a”

Note

  1. All the strings in the input will only contain lower-case letters.
  2. The size of the dictionary won’t exceed 1,000.
  3. The length of all the strings in the input won’t exceed 1,000.

Code

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
public String findLongestWord(String s, List<String> d) {
String result = "";
char[] array = s.toCharArray();

for (String word : d) {
if (word.length() < result.length() || (word.length() == result.length() && word.compareTo(result) > 0))
continue;

if (isValid(array, word.toCharArray()))
result = word;
}

return result;
}

private boolean isValid(char[] s, char[] w) {
int i = 0;
int j = 0;

while (i < s.length && j < w.length) {
if (s[i] == w[j])
j++;

i++;
}

return j == w.length;
}