leetcode力扣刷题打卡
题目:524. 通过删除字母匹配到字典里最长单词
描述:给你一个字符串 s 和一个字符串数组 dictionary ,找出并返回 dictionary 中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。
如果答案不止一个,返回长度最长且字母序最小的字符串。如果答案不存在,则返回空字符串。
思路:
1、先判断dictionary中的每个元素是不是s的子字符串;不是continue,是就进行比较,并记录最大长度和下标值;
3、注意还有不存在的情况,返回空数组。
原代码##
class Solution {
bool issubstr(string s, string sub) {
int n = s.size(), ind = 0;
for (int i = 0; i < n; ++i) {
if (s[i] == sub[ind]) {
ind++;
if (ind == sub.size()) break;
}
}
return ind == sub.size() ? true : false;
}
public:
string findLongestWord(string s, vector<string>& dictionary) {
vector <int> v;
int maxlen = 0, ans = -1;
for (int i = 0; i < dictionary.size(); ++i) {
int len = dictionary[i].size();
if (!issubstr(s, dictionary[i])) continue;
if (maxlen < len) {
maxlen = len;
ans = i;
} else if (maxlen == len) {
ans = dictionary[ans] < dictionary[i] ? ans : i;
}
}
return ans == -1 ? "" : dictionary[ans];
}
};