524 Longest Word in Dictionary through Deleting

1. Question

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 1:
1
Input: s = "abpcplea", d = ["ale","apple","monkey","plea"]
2
3
4
Output: "apple"
Copied!
Example 2:
1
Input: s = "abpcplea", d = ["a","b","c"]
2
3
Output: "a"
Copied!
Note:
  1. 1.
    All the strings in the input will only contain lower-case letters.
  2. 2.
    The size of the dictionary won't exceed 1,000.
  3. 3.
    The length of all the strings in the input won't exceed 1,000.

2. Implementation

(1) Two Pointers
1
class Solution {
2
public String findLongestWord(String s, List<String> d) {
3
if (s == null || s.length() == 0 || d.size() == 0) {
4
return "";
5
}
6
7
String res = "";
8
9
for (String word : d) {
10
if (word.length() > s.length()) {
11
continue;
12
}
13
14
if (isSubsequence(s, word)) {
15
if (word.length() > res.length() || (word.length() == res.length() && word.compareTo(res) < 0)) {
16
res = word;
17
}
18
}
19
}
20
return res;
21
}
22
23
public boolean isSubsequence(String s, String t) {
24
int tIndex = 0;
25
for (int i = 0; i < s.length() && tIndex < t.length(); i++) {
26
if (s.charAt(i) == t.charAt(tIndex)) {
27
++tIndex;
28
}
29
}
30
return tIndex == t.length();
31
}
32
}
Copied!

3. Time & Space Complexity

Two Pointers: 时间复杂度O(n), 空间复杂度O(1)