LeetCode 524.通过删除字母匹配到字典里最长单词
给你一个字符串 s 和一个字符串数组 dictionary ,找出并返回 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] 仅由小写英文字母组成
遍历字典里每个单词,然后对于单个单词,与s一起进行双序列双指针,看单词是否是s的子序列:
class Solution {
public:string findLongestWord(string s, vector<string>& dictionary) {int ansIdx = -1;for (int i = 0; i < dictionary.size(); ++i) {int sIdx = 0;int wordIdx = 0;string &word = dictionary[i];int wordSize = word.size();while (sIdx < s.size() && wordIdx < wordSize) {if (s[sIdx] == word[wordIdx]) {++wordIdx;}++sIdx;}if (wordIdx == wordSize) {// 更新答案if (ansIdx == -1 || wordSize > dictionary[ansIdx].size() || wordSize == dictionary[ansIdx].size() && word < dictionary[ansIdx]) {ansIdx = i;}}}return ansIdx == -1 ? "" : dictionary[ansIdx];}
};
如果字典的长度为n,s的长度为m,字典中单词的平均长度为l,则此算法时间复杂度为O(n(m+l)),因为需要遍历n个单词,每个单词需要m的时间判断是否匹配,以及最差需要l的时间判断是否是字母序最小的串;空间复杂度为O(1)。