leetcode-139-Word Break

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值