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 1:

``````Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]

Output:
"apple"
``````

Example 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.

``````class Solution {
public:
string findLongestWord(string s, vector<string>& d) {
sort(d.begin(), d.end(), [](string a, string b){
if (a.size() == b.size()) return a < b;
return a.size() > b.size();
});
for (string str : d) {
int i = 0;
for (char c : s) {
if (i < str.size() && c == str[i]) ++i;
}
if (i == str.size()) return str;
}
return "";
}
};
``````

``````class Solution {
public:
string findLongestWord(string s, vector<string>& d) {
string res = "";
for (string str : d) {
int i = 0;
for (char c : s) {
if (i < str.size() && c == str[i]) ++i;
}
if (i == str.size() && str.size() >= res.size()) {
if (str.size() > res.size() || str < res) {
res = str;
}
}
}
return res;
}
};
``````

https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/description/

https://discuss.leetcode.com/topic/80876/10-lines-solutions-for-c

https://discuss.leetcode.com/topic/80799/short-java-solutions-sorting-dictionary-and-without-sorting/2

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation