-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path140.cpp
More file actions
45 lines (39 loc) · 1015 Bytes
/
Copy path140.cpp
File metadata and controls
45 lines (39 loc) · 1015 Bytes
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
#include <unordered_map>
#include "common.h"
using namespace std;
class Solution {
public:
unordered_map<string, bool> memo;
vector<string> rst;
vector<string> wordBreak(string s, vector<string>& wordDict) {
unordered_map<char, vector<string>> candidate;
for (auto& s : wordDict) {
candidate[s[0]].push_back(s);
}
helper(candidate, s, "");
for (auto& s : rst) {
s = s.substr(1);
}
return rst;
}
void helper(unordered_map<char, vector<string>>& candidate, string s, string temp) {
if (s.length() == 0) {
rst.push_back(temp);
return;
}
const vector<string>& check = candidate[s[0]];
for (auto& word : check) {
string sub_str = s.substr(0, word.size());
if (sub_str != word) {
continue;
}
helper(candidate, s.substr(word.size()), temp + ' ' + word);
}
}
};
int main() {
Solution s;
vector<string> strs = {"cat", "cats", "and", "sand", "dog"};
s.wordBreak("catsanddog", strs);
return 0;
}