#include <iostream>
#include <string.h>
#include <unordered_set>
using namespace std;
class Solution {
private:
struct node {
bool end;
node *child[26];
node() {
end = false;
memset(child, 0, sizeof(child));
}
};
node *root;
public:
Solution():root(NULL) {}
bool wordBreak(string s, unordered_set<string>& wordDict) {
clearTree(root);
root = NULL;
root = new node();
for (auto it = wordDict.begin(); it != wordDict.end(); it++) {
node *current = root;
int counter = 0;
while (counter != it->length()) {
if (!current->child[(*it)[counter] - 'a']) {
current->child[(*it)[counter] - 'a'] = new node();
}
current = current->child[(*it)[counter] - 'a'];
counter++;
}
current->end = true;
}
return search(root, s);
}
//指针变量的引用形参
void clearTree(node *start) {
if (start != NULL) {
for (int i = 0; i < 26; i++) {
if (!start->child[i]) {
clearTree(start->child[i]);
}
}
delete start;
start = NULL;
}
}
bool search(node *start, string str) {
if (!start) {
return false;
}
if (str.length() == 0) {
return start->end;
}
if (!start->child[str[0] - 'a']) {
return false;
}
//深搜一个分支
if (search(start->child[str[0] - 'a'], str.c_str() + 1)) {
return true;
} else {
//从头开始
return search(root, str.c_str() + 1);
}
}
};
//"aaaaaaa" ["aaaa","aaa"]
//"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab"
//["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
int main(int argc, const char * argv[]) {
Solution s;
unordered_set<string> us ({"a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"});
cout << s.wordBreak("aaaaaaaaaaaaaaaaaaaaab", us) << endl;
cout << s.wordBreak("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", us) << endl;
return 0;
}
leetcode-139-Word Break
最新推荐文章于 2022-03-12 09:27:24 发布