blob: 3be45389b61e99be936021927708d3aef9d78944 (
plain)
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
|
#include "leetcode.h"
class Solution {
public:
string findLongestWord(string s, vector<string> &dictionary) {
string ans;
for (auto d : dictionary)
if (canForm(d, s))
if (d.size() > ans.size() || (d.size() == ans.size() && d < ans))
ans = d;
return ans;
}
private:
bool canForm(string w, string s) {
int w1 = 0, s1 = 0;
while (w1 < w.size() && s1 < s.size()) {
if (w[w1] == s[s1])
w1++;
s1++;
}
return w1 == w.size();
}
};
int main() {
Solution obj;
string s = "abpcplea";
vector<string> dictionary = {"ale", "apple", "monkey", "plea"};
cout << obj.findLongestWord(s, dictionary);
}
|