问题描述
给你一个字符串 s 和一个字符串数组 dictionary 作为字典,找出并返回字典中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
如果答案不止一个,返回长度最长且字典序最小的字符串。如果答案不存在,则返回空字符串。
输入输出
示例 1:
输入:s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
输出:"apple"
示例 2:
输入:s = "abpcplea", dictionary = ["a","b","c"]
输出:"a"
提示:
1 <= s.length <= 1000
1 <= dictionary.length <= 1000
1 <= dictionary[i].length <= 1000
s 和 dictionary[i] 仅由小写英文字母组成
笔记
string
1. t.at(i) 和 t[i]
2. s.compare(t)
s == t 0
s > t -1
s < t 1
3. sort(dictionary.begin(), dictionary.end(), cmp);
默认升序
cmp可以重写(默认升序)
代码
class Solution {
public:
static bool cmp(string &a,string &b){
if(a.size() == b.size())
return a.compare(b)<0;
return a.size()>b.size();
}
string findLongestWord(string s, vector<string>& dictionary) {
sort(dictionary.begin(), dictionary.end(), cmp);
string res = "";
for(string t : dictionary){
int i = 0, j = 0;
while(i < t.length() && j < s.length()){
if(t.at(i) == s.at(j)){
i++;
}
j++;
}
if(i == t.length()){
res = t;
break;
}
}
return res;
}
};