[LeetCode] Longest Word in Dictionary through Deleting

524. Longest Word in Dictionary through Deleting

Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
unordered_map<char, vector<int>> seq;
bool twoPointerCompare(string& origin, string& target) {//o(min(target.len, origin.len))
int j = 0;
for(int i = 0; i < origin.length() and j < target.length(); i++) {
if(origin[i] == target[j])
j++;
}

return target.length() == j;
}

bool binarySearchCompare(string& target) { //o(mlogn) is maximum
int mi = -1;
for(int i = 0; i < target.length(); i++) {
if(!seq.count(target[i])) return false; //early return

auto it = upper_bound(seq[target[i]].begin(), seq[target[i]].end(), mi);
if(it == seq[target[i]].end()) return false; //no match

mi = *it; //update
}
return true;
}

void seqMap(string& s) {
for(int i = 0; i < s.length(); i++) {
seq[s[i]].push_back(i);
}
}
public:
string findLongestWord(string s, vector<string>& dictionary) {
string res = "";
sort(dictionary.begin(), dictionary.end(), [](string& s1, string& s2){ //o(mlogm)
if(s1.length() == s2.length()) return s1 < s2;
return s1.length() > s2.length();
});

seqMap(s);

for(auto& dict: dictionary) {
if(binarySearchCompare(dict))
return dict;
}


return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/longest-word-in-dictionary-through-deleting/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.