美文网首页
(trie) 648. 单词替换

(trie) 648. 单词替换

作者: 来到了没有知识的荒原 | 来源:发表于2022-07-07 12:01 被阅读0次

648. 单词替换

const int N = 1e6+10;
int son[N][26], idx = 0;
int cnt[N];

class Solution {
public:
    void insert(string s){
        int p = 0;
        for(auto c: s){
            int u = c - 'a';
            if(!son[p][u]) son[p][u] = ++idx;
            p = son[p][u];
        }
        cnt[p] = 1;
    }
    string query(string s){
        int p = 0;
        string res = "";
        for(auto c: s){
            int u = c - 'a';
            if(!son[p][u]) return s;
            p = son[p][u];
            res += c;
            if(cnt[p]) return res;
        }
        return s;
    }
    string replaceWords(vector<string>& dictionary, string sentence) {
        memset(son, 0, sizeof son);
        memset(cnt, 0, sizeof cnt);
        for(auto s: dictionary){
            insert(s);
        }
        stringstream ssin(sentence);
        string res = "", w;
        while(ssin >> w){
            string curs = query(w);
            res += curs + " ";
        }
        if(res.size() && res.back()==' ')res.pop_back();
        return res;
    }
};

相关文章

  • (trie) 648. 单词替换

    648. 单词替换[https://leetcode.cn/problems/replace-words/]

  • Trie树

    一、定义 Trie树,又称为单词查找树,是一种树形结构(Trie一词源于单词Retrieval-取出)。Trie树...

  • hihoCoder#1014:Trie树

    建立Trie树,输出前缀单词个数。

  • 648.词根替换(Python)

    题目 难度:★★☆☆☆类型:字符串方法:哈希 力扣链接请移步本题传送门[https://leetcode-cn.c...

  • trie树

    文章内容来自 Trie树:应用于统计和排序Trie树 trie树又称:字典树、单词查找树、前缀树等,总之是一种树状...

  • 数据结构与算法(第一季):Trie

    一、概念 Trie 也叫做字典树、前缀树(Prefix Tree)、单词查找树。 Trie 搜索字符串的效率主要跟...

  • 树结构之Trie

    1. 什么是trie树 1.Trie树 (特例结构树)Trie树,又称单词查找树、字典树,是一种树形结构,是一种哈...

  • 数据结构-Trie

    ◼ Trie 也叫做字典树、前缀树(Prefix Tree)、单词查找树◼ Trie 搜索字符串的效率主要跟字符串...

  • Trie 和哈夫曼树

    Trie 也叫作字典树, 前缀树(Prefix Tree), 单词查找树 Trie 搜索字符串的效率跟字符串的长度...

  • (314)字典树与三向字典树-java实现

    引言 用java实现的单词树与三向单词树。 理论 参考: 单词查找树(Tries) Trie—单词查找树 代码(j...

网友评论

      本文标题:(trie) 648. 单词替换

      本文链接:https://www.haomeiwen.com/subject/hmxpbrtx.html