[Geeks for Geeks] Find largest word in dictionary

Find largest word in dictionary

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

  • Time : O(nx)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
bool match(string& s, string& t) {
if(s.length() < t.length()) return false;
int i = 0, j = 0, n = s.length(), m = t.length();
while(i < n and j < m) {
if(s[i] == t[j]) {
i++,j++;
} else i++;
}
return j == m;
}
public:
string findLongestWord(string S, vector<string> d) {
string res = "";
for(auto& t : d) {
if((t.length() > res.length() or (t.length() == res.length() and res > t)) and match(S, t)) {
res = t;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/find-largest-word-in-dictionary/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.