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 2 3 4 5
Input: s = "abpcplea", d = ["ale","apple","monkey","plea"]
Output: "apple"
Example 2:
1 2 3 4 5
Input: s = "abpcplea", d = ["a","b","c"]
Output: "a"
Note:
All the strings in the input will only contain lower-case letters.
The size of the dictionary won’t exceed 1,000.
The length of all the strings in the input won’t exceed 1,000.
for item in d: if(isSubstring(item, s)): res_list.append(item)
res = "" max_len = 0
for item in res_list: iflen(item) > max_len or (len(item) == max_len and item < res): res = item max_len = len(item) return res
比较简洁的 Python 代码
1 2 3 4 5
deffindLongestWord(self, s, d): defisSubsequence(x): it = iter(s) returnall(c in it for c in x) returnmax(sorted(filter(isSubsequence, d)) + [''], key=len)
publicclassSolution{ public String findLongestWord(String s, List<String> d){ String res = ""; if (s.length() == 0 || d.size() == 0) { return res; } for (String str : d) { int resLen = res.length(); int strLen = str.length(); if (isSequence(s, str) && (strLen > resLen || (strLen == resLen && str.compareTo(res) < 0))) { res = str; } } return res; } privatebooleanisSequence(String s, String d){ int i = 0; int j = 0; while (i < s.length() && j < d.length()) { while (i < s.length() && s.charAt(i) != d.charAt(j)) { i ++; } if (i < s.length()) { i ++; j ++; } } return j == d.length(); } }
简洁版的 Java 代码
1 2 3 4 5 6 7 8 9 10 11 12 13
public String findLongestWord(String s, List<String> d){ String longest = ""; for (String dictWord : d) { int i = 0; for (char c : s.toCharArray()) if (i < dictWord.length() && c == dictWord.charAt(i)) i++;
if (i == dictWord.length() && dictWord.length() >= longest.length()) if (dictWord.length() > longest.length() || dictWord.compareTo(longest) < 0) longest = dictWord; } return longest; }