給你一個字符串 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)。