[CareerCup] 18.8 Search String 搜尋字串

Grandyang發表於2016-05-09

 

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. 

 

這道題給我們一個字串s,和一個字串陣列T,讓我們找T中的每一個小字串在s中出現的位置,這道題很適合用字尾樹Suffix Tree來做,LeetCode中有幾道關於字首樹(Prefix Tree, Trie)的題,Implement Trie (Prefix Tree)Word Search II,和 Add and Search Word - Data structure design 。字首樹和字尾樹比較相似,都是很重要的資料結構,在解決特定問題時非常有效,具體講解請參見這個帖子。參見程式碼如下:

 

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

 

類似題目:

Implement Trie (Prefix Tree)

Word Search II

Add and Search Word - Data structure design 

 

參考資料:

http://blog.csdn.net/v_july_v/article/details/6897097

 

CareerCup All in One 題目彙總

相關文章