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) { 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) { int mi = -1 ; for (int i = 0 ; i < target.length (); i++) { if (!seq.count (target[i])) return false ; auto it = upper_bound (seq[target[i]].begin (), seq[target[i]].end (), mi); if (it == seq[target[i]].end ()) return false ; mi = *it; } 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){ 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; } };