C++實現LeetCode(648.替換單詞)

[LeetCode] 648.Replace Words 替換單詞

In English, we have a concept called root, which can be followed by some other words to form another longer word – let’s call this word successor. For example, the root an, followed by other, which can form another word another.

Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.

You need to output the sentence after the replacement.

Example 1:

Input: dict = [“cat”, “bat”, “rat”]
sentence = “the cattle was rattled by the battery”
Output: “the cat was rat by the bat”

Note:

  1. The input will only have lower-case letters.
  2. 1 <= dict words number <= 1000
  3. 1 <= sentence words number <= 1000
  4. 1 <= root length <= 100
  5. 1 <= sentence words length <= 1000

這道題給瞭我們一個前綴字典,又給瞭一個句子,讓我們將句子中較長的單詞換成其前綴(如果在前綴字典中存在的話)。我們對於句子中的一個長單詞如何找前綴呢,是不是可以根據第一個字母來快速定位呢,比如cattle這個單詞的首字母是c,那麼我們在前綴字典中找所有開頭是c的前綴,為瞭方便查找,我們將首字母相同的前綴都放到同一個數組中,總共需要26個數組,所以我們可以定義一個二維數組來裝這些前綴。還有,我們希望短前綴在長前綴的前面,因為題目中要求用最短的前綴來替換單詞,所以我們可以先按單詞的長度來給所有的前綴排序,然後再依次加入對應的數組中,這樣就可以保證短的前綴在前面。

下面我們就要來遍歷句子中的每一個單詞瞭,由於C++中沒有split函數,所以我們就采用字符串流來提取每一個單詞,對於遍歷到的單詞,我們根據其首字母查找對應數組中所有以該首字母開始的前綴,然後直接用substr函數來提取單詞中和前綴長度相同的子字符串來跟前綴比較,如果二者相等,說明可以用前綴來替換單詞,然後break掉for循環。別忘瞭單詞之前還要加上空格,參見代碼如下:

解法一:

class Solution {
public:
    string replaceWords(vector<string>& dict, string sentence) {
        string res = "", t = "";
        vector<vector<string>> v(26);
        istringstream is(sentence);
        sort(dict.begin(), dict.end(), [](string &a, string &b) {return a.size() < b.size();});
        for (string word : dict) {
            v[word[0] - 'a'].push_back(word);
        }
        while (is >> t) {
            for (string word : v[t[0] - 'a']) {
                if (t.substr(0, word.size()) == word) {
                    t = word;
                    break;
                }
            }
            res += t + " ";
        }
        res.pop_back();
        return res;
    }
};

你以為想出瞭上面的解法,這道題就算做完瞭?? Naive! ! ! 這道題最好的解法其實是用前綴樹(Trie / Prefix Tree)來做,關於前綴樹使用之前有一道很好的入門題Implement Trie (Prefix Tree)。瞭解瞭前綴樹的原理機制,那麼我們就可以發現這道題其實很適合前綴樹的特點。我們要做的就是把所有的前綴都放到前綴樹裡面,而且在前綴的最後一個結點的地方將標示isWord設為true,表示從根節點到當前結點是一個前綴,然後我們在遍歷單詞中的每一個字母,我們都在前綴樹查找,如果當前字母對應的結點的表示isWord是true,我們就返回這個前綴,如果當前字母對應的結點在前綴樹中不存在,我們就返回原單詞,這樣就能完美的解決問題瞭。所以啊,以後遇到瞭有關前綴或者類似的問題,一定不要忘瞭前綴樹這個神器喲~

解法二:

class Solution {
public:
    class TrieNode {
    public:
        bool isWord;
        TrieNode *child[26];
        TrieNode(): isWord(false) {
            for (auto &a : child) a = NULL;
        }
    };
    
    string replaceWords(vector<string>& dict, string sentence) {
        string res = "", t = "";
        istringstream is(sentence);
        TrieNode *root = new TrieNode();
        for (string word : dict) {
            insert(root, word);
        }
        while (is >> t) {
            if (!res.empty()) res += " ";
            res += findPrefix(root, t);
        }
        return res;
    }
    
    void insert(TrieNode* node, string word) {
        for (char c : word) {
            if (!node->child[c - 'a']) node->child[c - 'a'] = new TrieNode();
            node = node->child[c - 'a'];
        }
        node->isWord = true;
    }
    
    string findPrefix(TrieNode* node, string word) {
        string cur = "";
        for (char c : word) {
            if (!node->child[c - 'a']) break;
            cur.push_back(c);
            node = node->child[c - 'a'];
            if (node->isWord) return cur;
        }
        return word;
    }
};

類似題目:

Implement Trie (Prefix Tree)

參考資料:

https://discuss.leetcode.com/topic/97203/trie-tree-concise-java-solution-easy-to-understand

到此這篇關於C++實現LeetCode(648.替換單詞)的文章就介紹到這瞭,更多相關C++實現替換單詞內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: