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:
Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]
Output:
"apple"
Example 2:
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.
2. Solution
直接用输入字符串去匹配字典中的每一个字符串。时间复杂度O(nk),n为字典中字符串的个数,k为输入字符串的长度。
3. Code
class Solution {
public:
string findLongestWord(string s, vector<string>& d) {
string longest = "";
for (string str : d) {
int j = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == str[j])
j++;
}
// 字符串匹配完以及长度大于等于
if (j == str.length() && str.length() >= longest.length()) {
// 要么更长,如果一样长,那么就看字典序
if (str.length() > longest.length() || str < longest)
longest = str;
}
}
return longest;
}
};