题目
给你一个字符串 s 和一个字符串数组 dictionary ,找出并返回 dictionary 中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
如果答案不止一个,返回长度最长且字母序最小的字符串。如果答案不存在,则返回空字符串。
示例
题解
不难 就是比较复杂
class Solution {
public:
bool isstr(string dictionary,string s){
int i = 0,j = 0;
while(i < s.size() && j < dictionary.size()){
if(s[i] == dictionary[j]){
i++;j++;
}
else i++;
}
if(j == dictionary.size()) return true;
else return false;
}
string findLongestWord(string s, vector<string>& dictionary) {
int max = 0;
int index = -1;
for(int i = 0;i < dictionary.size();i++){
if(isstr(dictionary[i],s)){
if(dictionary[i].size() > max){
max = dictionary[i].size();
index = i;
}
else if((dictionary[i].size() == max)){
int p = 0,q = 0;
while(p < max && q < max){
if(dictionary[i][p] == dictionary[index][q]){
p++;q++;
}
else if(dictionary[i][p] < dictionary[index][q]){
index = i;
break;
}
else break;
}
}
}
}
if(index == -1)return "";
else return dictionary[index];
}
};