[CareerCup] 18.8 Search String 搜索字符串

简介:

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

本文转自博客园Grandyang的博客,原文链接: 搜索字符串[CareerCup] 18.8 Search String,如需转载请自行联系原博主。

相关文章
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
326 100
|
3月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
440 99
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
3月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
4月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
288 92
|
5月前
|
自然语言处理 Java Apache
在Java中将String字符串转换为算术表达式并计算
具体的实现逻辑需要填写在 `Tokenizer`和 `ExpressionParser`类中,这里只提供了大概的框架。在实际实现时 `Tokenizer`应该提供分词逻辑,把输入的字符串转换成Token序列。而 `ExpressionParser`应当通过递归下降的方式依次解析
339 14
|
9月前
|
数据处理
鸿蒙开发:ArkTs字符串string
字符串类型是开发中非常重要的一个数据类型,除了上述的方法概述之外,还有String对象,正则等其他的用处,我们放到以后得篇章中讲述。
523 19
|
9月前
|
Java 程序员
课时16:String字符串
课时16介绍了Java中的String字符串。在Java中,字符串使用`String`类表示,并用双引号定义。例如:`String str = &quot;Hello world!&quot;;`。字符串支持使用“+”进行连接操作,如`str += &quot;world&quot;;`。需要注意的是,当“+”用于字符串与其他数据类型时,其他类型会先转换为字符串再进行连接。此外,字符串中可以使用转义字符(如`\t`、`\n`)进行特殊字符的处理。掌握这些基本概念对Java编程至关重要。
135 0