LeetCode 648 Replace Words

标签: 设计数据结构 LeetCode 发布于:2022-02-10 20:21:57 编辑于:2022-02-10 20:36:58 浏览量:913

概述

https://leetcode.com/problems/replace-words/

基于前缀树的实现

在将句子分割成单词时,别忘记在循环结束后收集最后一个单词。

class Solution {
public:
    class Node {
    public:
        Node* children[26];
        bool end = false;
        Node() : children() {}
    };
    
    string replaceWords(vector<string>& dictionary, string sentence) {
        auto root = new Node;
        for (auto& word : dictionary) {
            auto node = root;
            for (auto c : word) {
                if (!node->children[c - 'a']) {
                    node->children[c - 'a'] = new Node;
                }
                node = node->children[c - 'a'];
            }
            node->end = true;
        }
        
        vector<string> words;
        string t;
        for (auto c : sentence) {
            if (c == ' ') {
                words.push_back(t);
                t = "";
            } else {
                t += c;
            }
        }
        words.push_back(t);
        
        string res;
        for (auto& word : words) {
            auto node = root;
            string prefix;
            for (auto c : word) {
                if (node->children[c - 'a']) {
                    prefix += c;
                    node = node->children[c - 'a'];
                    if (node->end) break;
                } else {
                    prefix = word;
                    break;
                }
            }
            res += prefix + " ";
        }
        res.pop_back();
        return res;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/