Longest Word in Dictionary through Deleting LeetCode solution in C++

1
class Solution {
2
private:
3
// checks whether the string word is a subsequence of s
4
bool isSubSeq(string &s, string &word) {
5
int start = 0;
6
for (int i = 0; i < s.size(); i++) {
7
if (s[i] == word[start]) {
8
// every character of word occurs in s, therefore we return true
9
if (++start == word.size()) {
10
return true;
11
}
12
}
13
}
14
return false;
15
}
16

17
public:
18
string findLongestWord(string s, vector<string> &dictionary) {
19
string ans = "";
20
for (string word : dictionary) {
21
if (word.size() >= ans.size() and isSubSeq(s, word)) {
22
if (word.size() > ans.size()) {
23
ans = word;
24
} else if (word.size() == ans.size() and word < ans) {
25
ans = word;
26
}
27
}
28
}
29
return ans;
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0