**524. Longest Word in Dictionary through Deleting
Medium
305
165
Favorite
删除 s 中的一些字符,使得它构成字符串列表 d 中的一个字符串,找出能构成的最长字符串。如果有多个相同长度的结果,返回字典序的最小字符串。
Share
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”**
代码
class Solution {
public:
string findLongestWord(string s, vector<string>& d) {
string longWord="";//初始化空字符串
for(int i=0;i<d.size();i++){//遍历vector里的每一个单词
int L1=longWord.length();//当前包含的单词的长度 题目要求最长字符串单词
int L2=d[i].size();//单词的长度
//如果当前最长单词大于当前vector单词‘
//或者’虽然相等但字典符小,比较下一个单词
if(L1>L2||(L1==L2&&longWord<=d[i]))
continue;
//类似双指针
int one=0,two=0;
//比较字符是否相同,如果相同 比较下一个,如果不同,字符串地址加1
while(one<s.length()&&two<L2){
if(s[one]==d[i][two])
two++;
one++;
}
//当vector单词相等 赋值给最大单词
if(two==L2)
longWord=d[i];
}
return longWord;
}
};