码迷,mamicode.com
首页 > 其他好文 > 详细

[CareerCup] 18.8 Search String 搜索字符串

时间:2016-05-09 06:54:27      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

 

18.8 Given a string s and an array of smaller strings T, design a method to search s for each small string in T. 

 

 

class SuffixTreeNode {
public:
    unordered_map<char, SuffixTreeNode*> children;
    char value;
    vector<int> indexes;
    
    void insertString(string s, int idx) {
        indexes.push_back(idx);
        if (!s.empty()) {
            value = s[0];
            SuffixTreeNode *child;
            if (children.count(value)) {
                child = children[value];
            } else {
                child = new SuffixTreeNode();
                children[value] = child;
            }
            string remainder = s.substr(1);
            child->insertString(remainder, idx);
        }
    }
    
    vector<int> search(string s) {
        if (s.empty()) return indexes;
        char first = s[0];
        if (children.count(first)) {
            string remainder = s.substr(1);
            return children[first]->search(remainder);
        }
        return {};
    }
};

class SuffixTree {
public:
    SuffixTreeNode *root = new SuffixTreeNode();
    
    SuffixTree(string s) {
        for (int i = 0; i < s.size(); ++i) {
            string suffix = s.substr(i);
            root->insertString(suffix, i);
        }
    }
    
    vector<int> search(string s) {
        return root->search(s);
    }
};

 

参考资料:

从Trie树(字典树)谈到后缀树

 

CareerCup All in One 题目汇总

[CareerCup] 18.8 Search String 搜索字符串

标签:

原文地址:http://www.cnblogs.com/grandyang/p/5472464.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!