Tag Archives: Trie

LeetCode Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree

LeetCode Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree

Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree. 

We get the given string from the concatenation of an array of integers arr and the concatenation of all values of the nodes along a path results in a sequence in the given binary tree.

Example 1:

Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,0,1]
Output: true
Explanation: 
The path 0 -> 1 -> 0 -> 1 is a valid sequence (green color in the figure). 
Other valid sequences are: 
0 -> 1 -> 1 -> 0 
0 -> 0 -> 0

Example 2:

Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,0,1]
Output: false 
Explanation: The path 0 -> 0 -> 1 does not exist, therefore it is not even a sequence.

Example 3:

Input: root = [0,1,0,0,1,0,null,null,1,0,0], arr = [0,1,1]
Output: false
Explanation: The path 0 -> 1 -> 1 is a sequence, but it is not a valid sequence.

Constraints:

  • 1 <= arr.length <= 5000
  • 0 <= arr[i] <= 9
  • Each node’s value is between [0 – 9].

给定一棵二叉树,和一个数组,问树中从根节点到叶子节点能否组成给定数组。

简单题,本质就是Trie树,直接DFS查找即可,代码如下:

class Solution {
public:
	bool dfs(TreeNode* root, vector<int>& arr, int idx) {
		int n = arr.size();
		if (idx >= n)return false;
		if (root->val == arr[idx] && root->left == NULL && root->right == NULL && idx == n - 1)return true;
		if (root->val != arr[idx])return false;
		bool left = false, right = false;
		if (root->left != NULL)left = dfs(root->left, arr, idx + 1);
		if (root->right != NULL)right = dfs(root->right, arr, idx + 1);
		return left || right;
	}
	bool isValidSequence(TreeNode* root, vector<int>& arr) {
		if (root == NULL)return false;
		return dfs(root, arr, 0);
	}
};

本代码提交AC,用时104MS。

hihoCoder 1551-合并子目录

hihoCoder 1551-合并子目录

#1551 : 合并子目录

时间限制:10000ms
单点时限:1000ms
内存限制:256MB

描述

小Hi的电脑的文件系统中一共有N个文件,例如: /hihocoder/offer22/solutions/p1 /hihocoder/challenge30/p1/test /game/moba/dota2/uninstall 小Hi想统计其中一共有多少个不同的子目录。上例中一共有8个不同的子目录: /hihocoder /hihocoder/offer22 /hihocoder/offer22/solutions /hihocoder/challenge30 /hihocoder/challenge30/p1 /game /game/moba /game/moba/dota2/

输入

第一行包含一个整数N (1 ≤ N ≤ 10000) 以下N行每行包含一个字符串,代表一个文件的绝对路径。保证路径从根目录”/”开始,并且文件名和目录名只包含小写字母和数字。 对于80%的数据,N个文件的绝对路径长度之和不超过10000 对于100%的数据,N个文件的绝对路径长度之和不超过500000

输出

一个整数代表不同子目录的数目。
样例输入
3
/hihocoder/offer22/solutions/p1
/hihocoder/challenge30/p1/test
/game/moba/dota2/uninstall
样例输出
8

给定很多个文件的绝对路径,问从这些文件的绝对路径中,我们可以知道其一共有多少个不同文件夹出现过。 常规思路很简单,直接解析每个文件所在的每一级文件夹路径,存到一个set里面,最后返回unordered_set的大小。但是这种方法TLE,看了一下,内存基本也用完了。因为对于100%的数据,路径长度太长了,hash的时间和空间都随之增长。 后来马上想到,路径问题是一层一层的,有可能很多文件的路径前缀都是相同的,那么我们可以构建一个Trie树,每个节点仅是当前文件夹的名称。最后我们统计一下构建好的Trie树的节点个数,就是文件夹的个数。 完整代码如下: [cpp] #include<algorithm> #include<vector> #include<iostream> #include<unordered_map> #include<unordered_set> #include<string> #include<set> #include<map> #include<queue> using namespace std; typedef long long ll; struct Node { string key_; map<string, Node*> children_; Node(string key) :key_(key) {}; }; int main() { //freopen("input.txt", "r", stdin); int n; scanf("%d\n", &n); string line; Node* root = new Node(""); while (n–) { getline(cin, line); int pre = 0; int pos = line.find(‘//’); Node* cur = root; while (pos != string::npos) { if (pos != 0) { string tmp = line.substr(pre + 1, pos – pre – 1); if (cur->children_[tmp] == NULL) { cur->children_[tmp] = new Node(tmp); } cur = cur->children_[tmp]; } pre = pos; pos = line.find(‘//’, pos + 1); } } ll ans = 0; queue<Node*> q; q.push(root); while (!q.empty()) { Node* cur = q.front(); q.pop(); ++ans; for (auto it : cur->children_) { q.push(it.second); } } printf("%lld\n", ans – 1); return 0; } [/cpp] 本代码提交AC,用时126MS。]]>

LeetCode Replace Words

LeetCode 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 rootforming 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

给定一个词典和一个句子,词典是一系列的词根,要求把句子中的每个词替换成其最短词根(如果有词根的话)。 简单题,明显是Trie树的应用。首先把词典中的所有词根建一个Trie树,然后对句子中的每个单词,去Trie树中查找,返回最先找到的词根(也就是最短的词根);如果该词不在Trie树中,则说明不存在词根,直接用原来的单词。 完整代码如下: [cpp] const int kMaxN = 26; class Solution { private: struct Node { bool is_word_; vector<Node*> children_; Node() :is_word_(false) { for (int i = 0; i < kMaxN; ++i) children_.push_back(NULL); } }; Node *root_; void InsertWord(const string& word) { Node *cur = root_; for (const auto& c : word) { int idx = c – ‘a’; if (cur->children_[idx] == NULL)cur->children_[idx] = new Node(); cur = cur->children_[idx]; } cur->is_word_ = true; } void ConstructTree(const vector<string>& dict) { root_ = new Node(); for (const auto& w : dict) { InsertWord(w); } } string SearchTree(const string& word) { Node *cur = root_; string ans = ""; for (const auto& c : word) { int idx = c – ‘a’; if (cur->children_[idx] == NULL)return ""; cur = cur->children_[idx]; ans.push_back(c); if (cur->is_word_)return ans; } return ""; } public: string replaceWords(vector<string>& dict, string sentence) { ConstructTree(dict); string ans = ""; int i = 0, n = sentence.size(); for (int j = 0; j <= n; ++j) { if (j == n || sentence[j] == ‘ ‘) { string successor = sentence.substr(i, j – i); string root = SearchTree(successor); if (root == "") ans += successor + " "; else ans += root + " "; i = j + 1; } } return ans.substr(0, ans.size() – 1); } }; [/cpp] 本代码提交AC,用时98MS。]]>

LeetCode Design Search Autocomplete System

LeetCode Design Search Autocomplete System Design a search autocomplete system for a search engine. Users may input a sentence (at least one word and end with a special character '#'). For each character they type except ‘#’, you need to return the top 3 historical hot sentences that have prefix the same as the part of sentence already typed. Here are the specific rules:

  1. The hot degree for a sentence is defined as the number of times a user typed the exactly same sentence before.
  2. The returned top 3 hot sentences should be sorted by hot degree (The first is the hottest one). If several sentences have the same degree of hot, you need to use ASCII-code order (smaller one appears first).
  3. If less than 3 hot sentences exist, then just return as many as you can.
  4. When the input is a special character, it means the sentence ends, and in this case, you need to return an empty list.
Your job is to implement the following functions: The constructor function: AutocompleteSystem(String[] sentences, int[] times): This is the constructor. The input is historical dataSentences is a string array consists of previously typed sentences. Times is the corresponding times a sentence has been typed. Your system should record these historical data. Now, the user wants to input a new sentence. The following function will provide the next character the user types: List<String> input(char c): The input c is the next character typed by the user. The character will only be lower-case letters ('a' to 'z'), blank space (' ') or a special character ('#'). Also, the previously typed sentence should be recorded in your system. The output will be the top 3 historical hot sentences that have prefix the same as the part of sentence already typed.   Example: Operation: AutocompleteSystem([“i love you”, “island”,”ironman”, “i love leetcode”], [5,3,2,2]) The system have already tracked down the following sentences and their corresponding times: "i love you" : 5 times "island" : 3 times "ironman" : 2 times "i love leetcode" : 2 times Now, the user begins another search: Operation: input(‘i’) Output: [“i love you”, “island”,”i love leetcode”] Explanation: There are four sentences that have prefix "i". Among them, “ironman” and “i love leetcode” have same hot degree. Since ' ' has ASCII code 32 and 'r' has ASCII code 114, “i love leetcode” should be in front of “ironman”. Also we only need to output top 3 hot sentences, so “ironman” will be ignored. Operation: input(‘ ‘) Output: [“i love you”,”i love leetcode”] Explanation: There are only two sentences that have prefix "i ". Operation: input(‘a’) Output: [] Explanation: There are no sentences that have prefix "i a". Operation: input(‘#’) Output: [] Explanation: The user finished the input, the sentence "i a" should be saved as a historical sentence in system. And the following input will be counted as a new search.   Note:
  1. The input sentence will always start with a letter and end with ‘#’, and only one blank space will exist between two words.
  2. The number of complete sentences that to be searched won’t exceed 100. The length of each sentence including those in the historical data won’t exceed 100.
  3. Please use double-quote instead of single-quote when you write test cases even for a character input.
  4. Please remember to RESET your class variables declared in class AutocompleteSystem, as static/class variables are persisted across multiple test cases. Please see herefor more details.

本题要求实现一个搜索引擎的自动补全功能,正好是我想在我的新闻搜索引擎里实现的功能。首先会给出一些历史数据,就是哪些句子被访问了多少次。现在模拟用户输入,每输入一个字符,给出以输入的所有字符为前缀的历史句子,并且只给出被访频率前3的句子作为自动补全的候选。 Trie树的应用题。Trie树的节点属性包含is_sentence_以该字符结尾是否是一个句子,cnt_该句子的频率。首先把历史数据插入到Trie树中,记录好相应的is_sentence_和cnt_。 用一个成员变量cur_sentence_记录当前输入的字符串前缀。查找的时候,用cur_sentence_在Trie树中找,先找到这个前缀,然后在26个字母+一个空格中递归查找所有孩子节点,把能形成句子的字符串及其频率插入到一个优先队列中。该优先队列先以句子频率排序,如果频率相等,再以字典序排列。这样我们直接从优先队列中取出前三个堆顶句子,就是自动补全的候选。 如果遇到#,说明输入结束,把cur_sentence_及其频率1也插入到Trie树中。注意插入之后树中节点的频率是累加的,即第34行。 注意AutocompleteSystem类初始化的时候需要清空cur_sentence_和Trie树,更多的细节请看代码中的caution。 [cpp] const int N = 26; class AutocompleteSystem { private: struct Node { bool is_sentence_; int cnt_; vector<Node*> children_; Node() :is_sentence_(false), cnt_(0){ for (int i = 0; i < N + 1; ++i)children_.push_back(NULL); } }; Node *root; string cur_sentence_; struct Candidate { int cnt_; string sentence_; Candidate(int &cnt, string &sentence) :cnt_(cnt), sentence_(sentence) {}; bool operator<(const Candidate& cand) const { return (cnt_ < cand.cnt_) || (cnt_ == cand.cnt_&&sentence_ > cand.sentence_); // caution } }; void AddSentence(const string& sentence, const int& time) { Node *cur = root; for (const auto& c : sentence) { int idx = c – ‘a’; if (c == ‘ ‘)idx = N; if (cur->children_[idx] == NULL)cur->children_[idx] = new Node(); cur = cur->children_[idx]; } cur->is_sentence_ = true; cur->cnt_ += time; // caution } void FindSentences(Node *root, string &sentence, priority_queue<Candidate>& candidates) { if (root != NULL&&root->is_sentence_)candidates.push(Candidate(root->cnt_, sentence)); if (root == NULL)return; for (int i = 0; i < N + 1; ++i) { if (root->children_[i] != NULL) { if (i == N) sentence.push_back(‘ ‘); else sentence.push_back(‘a’ + i); FindSentences(root->children_[i], sentence, candidates); sentence.pop_back(); } } } void StartWith(priority_queue<Candidate>& candidates) { Node *cur = root; for (const auto& c : cur_sentence_) { int idx = c – ‘a’; if (c == ‘ ‘)idx = N; if (cur->children_[idx] == NULL)return; cur = cur->children_[idx]; } string sentence = cur_sentence_; FindSentences(cur, sentence, candidates); } public: AutocompleteSystem(vector<string> sentences, vector<int> times) { root = new Node(); // caution cur_sentence_ = ""; // caution for (int i = 0; i < sentences.size(); ++i)AddSentence(sentences[i], times[i]); } vector<string> input(char c) { if (c == ‘#’) { AddSentence(cur_sentence_, 1); // caution cur_sentence_ = ""; // caution return{}; } else { cur_sentence_.push_back(c); priority_queue<Candidate> candidates; StartWith(candidates); if (candidates.empty())return{}; vector<string> ans; while (!candidates.empty()) { ans.push_back(candidates.top().sentence_); candidates.pop(); if (ans.size() == 3)break; } return ans; } } }; [/cpp] 本代码提交AC,用时329MS。]]>

LeetCode Add and Search Word – Data structure design

211. Add and Search Word – Data structure design 211. Add and Search Word – Data structure design

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

Example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

Note:
You may assume that all words are consist of lowercase letters a-z. 211. Add and Search Word – Data structure design


实现一个字典,要求可以插入单词和搜索单词,并且支持一种正则表达式,即点号’.’表示任意一个字符。 本题明显是用Trie树来做,插入和搜索普通字符串的方法和Trie树是一模一样的。 唯一需要注意的是搜索带点号的字符串,此时用递归来做,递归的出口是,当遍历到字符串的最后一个字符时,根据是否为点号进行判断。递归向下的过程也是分是否为点号的,如果是点号,则需要尝试26种递归路径。想清楚这个逻辑之后,代码就很好写了。 完整代码如下:

const int N = 26;
class WordDictionary {
private:
    struct Node {
        bool isWord;
        vector<Node*> children;
        Node(bool i)
            : isWord(i)
        {
            for (int i = 0; i < N; ++i)
                children.push_back(NULL);
        };
    };
    Node* root;
    bool search(const string& word, int i, Node* root)
    {
        if (root == NULL)
            return false;
        int idx = word[i] – ‘a’;
        if (i == word.size() – 1) {
            if (word[i] != ‘.’)
                return root->children[idx] != NULL && root->children[idx]->isWord;
            else {
                for (int j = 0; j < N; ++j) {
                    if (root->children[j] != NULL && root->children[j]->isWord)
                        return true;
                }
                return false;
            }
        }
        if (word[i] != ‘.’)
            return search(word, i + 1, root->children[idx]);
        else {
            for (int j = 0; j < N; ++j) {
                if (search(word, i + 1, root->children[j]))
                    return true;
            }
            return false;
        }
    }
public: /** Initialize your data structure here. */
    WordDictionary() { root = new Node(false); } /** Adds a word into the data structure. */
    void addWord(string word)
    {
        Node* cur = root;
        for (const auto& c : word) {
            int idx = c – ‘a’;
            if (cur->children[idx] == NULL)
                cur->children[idx] = new Node(false);
            cur = cur->children[idx];
        }
        cur->isWord = true;
    } /** Returns if the word is in the data structure. A word could contain the dot character ‘.’ to represent any one letter. */
    bool search(string word)
    {
        Node* cur = root;
        return search(word, 0, cur);
    }
};

本代码提交AC,用时105MS。

LeetCode Implement Trie (Prefix Tree)

208. Implement Trie (Prefix Tree)

Implement a trie with insertsearch, and startsWith methods.

Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");   
trie.search("app");     // returns true

Note:

  • You may assume that all inputs are consist of lowercase letters a-z.
  • All inputs are guaranteed to be non-empty strings.

本题要求实现只包含26个小写字母的trie树。因为之前做过hihoCoder 1014-Trie树,所以实现起来并不费劲。 定义一个Node结构体,包含三个成员,char c表示该Node的字符,bool isWord表示以该Node结尾是否能构成一个单词,children表示该Node的26个孩子。 初始化的时候就初始化一个根节点。 插入一个单词时,不断从根节点往下创建节点,到最后一个字符所在节点时,标记isWord为true。 搜索一个单词时,也是不断从根节点往下搜索,如果到单词尾所在的Node的isWord为true,说明找到该单词,否则要么到不了最后一个字符,要么到了最后一个字符,isWord为false,都表示搜索失败。 搜索是否有某个前缀的单词存在,和搜索一个单词几乎一样,只不过最后返回时,不需要判断isWord是否为true,只要能到达prefix的最后一个字符的Node,说明后面肯定有以该字符串为前缀的单词存在。 完整代码如下:

const int MAXN = 26;
class Trie {
private:
    struct Node {
        char c;
        bool isWord;
        Node(char c_, bool isWord_)
            : c(c_)
            , isWord(isWord_)
        {
            for (int i = 0; i < MAXN; ++i)
                children.push_back(NULL);
        };
        vector<Node*> children;
    };
    Node* root;
public: /** Initialize your data structure here. */
    Trie() { root = new Node(‘ ‘, true); } /** Inserts a word into the trie. */
    void insert(string word)
    {
        Node* cur = root;
        for (int i = 0; i < word.size(); ++i) {
            int idx = word[i] – ‘a’;
            if (cur->children[idx] == NULL)
                cur->children[idx] = new Node(word[i], false);
            cur = cur->children[idx];
        }
        cur->isWord = true;
    } /** Returns if the word is in the trie. */
    bool search(string word)
    {
        Node* cur = root;
        for (int i = 0; i < word.size(); ++i) {
            int idx = word[i] – ‘a’;
            if (cur->children[idx] == NULL)
                return false;
            cur = cur->children[idx];
        }
        return cur->isWord;
    } /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix)
    {
        Node* cur = root;
        for (int i = 0; i < prefix.size(); ++i) {
            int idx = prefix[i] – ‘a’;
            if (cur->children[idx] == NULL)
                return false;
            cur = cur->children[idx];
        }
        return true;
    }
};

本代码提交AC,用时118MS。

hihoCoder 1014-Trie树

hihoCoder 1014-Trie树 #1014 : Trie树 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi和小Ho是一对好朋友,出生在信息化社会的他们对编程产生了莫大的兴趣,他们约定好互相帮助,在编程的学习道路上一同前进。 这一天,他们遇到了一本词典,于是小Hi就向小Ho提出了那个经典的问题:“小Ho,你能不能对于每一个我给出的字符串,都在这个词典里面找到以这个字符串开头的所有单词呢?” 身经百战的小Ho答道:“怎么会不能呢!你每给我一个字符串,我就依次遍历词典里的所有单词,检查你给我的字符串是不是这个单词的前缀不就是了?” 小Hi笑道:“你啊,还是太年轻了!~假设这本词典里有10万个单词,我询问你一万次,你得要算到哪年哪月去?” 小Ho低头算了一算,看着那一堆堆的0,顿时感觉自己这辈子都要花在上面了… 小Hi看着小Ho的囧样,也是继续笑道:“让我来提高一下你的知识水平吧~你知道树这样一种数据结构么?” 小Ho想了想,说道:“知道~它是一种基础的数据结构,就像这里说的一样!” 小Hi满意的点了点头,说道:“那你知道我怎么样用一棵树来表示整个词典么?” 小Ho摇摇头表示自己不清楚。 提示一:Trie树的建立 “你看,我们现在得到了这样一棵树,那么你看,如果我给你一个字符串ap,你要怎么找到所有以ap开头的单词呢?”小Hi又开始考校小Ho。 “唔…一个个遍历所有的单词?”小Ho还是不忘自己最开始提出来的算法。 “笨!这棵树难道就白构建了!”小Hi教训完小Ho,继续道:“看好了!” 提示二:如何使用Trie树 提示三:在建立Trie树时同时进行统计! “那么现在!赶紧去用代码实现吧!”小Hi如是说道 输入 输入的第一行为一个正整数n,表示词典的大小,其后n行,每一行一个单词(不保证是英文单词,也有可能是火星文单词哦),单词由不超过10个的小写英文字母组成,可能存在相同的单词,此时应将其视作不同的单词。接下来的一行为一个正整数m,表示小Hi询问的次数,其后m行,每一行一个字符串,该字符串由不超过10个的小写英文字母组成,表示小Hi的一个询问。 在20%的数据中n, m<=10,词典的字母表大小<=2. 在60%的数据中n, m<=1000,词典的字母表大小<=5. 在100%的数据中n, m<=100000,词典的字母表大小<=26. 本题按通过的数据量排名哦~ 输出 对于小Hi的每一个询问,输出一个整数Ans,表示词典中以小Hi给出的字符串为前缀的单词的个数。 样例输入 5 babaab babbbaaaa abba aaaaabaa babaababb 5 babb baabaaa bab bb bbabbaab 样例输出 1 3


这一题题目提示得很清楚,使用Trie树,无奈本人才疏学浅,在看这个题之前不知道什么是Trie树,果断百度之,大意是Trie树是一棵字典树,根节点不存储字母,其余所有节点存储一个字母,所以它最多是一棵26叉树;从根节点到某个节点的一次遍历就是一个单词,这样的数据结构很适合用来字符串查找或者前缀匹配。 常规的Trie树定义如下: [cpp] #define MAX 26 typedef struct TrieNode //Trie结点声明 { bool isStr; //标记该结点处是否构成单词 struct TrieNode *next[MAX]; //儿子分支 }Trie; [/cpp] 关于常规Trie树的详细介绍请看此博文。 Trie树节点中的isStr是为了查找单词方便而定义的,但是本题只是为了给出以某字符串为前缀的单词的个数,也就是说我们查找的时候只是查找前缀,而不是查找一个完整的单词,所以可以不要isStr成员。 之前看《算法导论》第14章:数据结构的扩张,其中讲到一种顺序统计树的数据结构,该结构就是一棵红黑树,只是在每个节点中额外增加了一个size属性来记录以该节点为根节点的树子树的节点个数。利用这种数据结构可以在O(lgn)时间复杂度内找到第i小的关键字,真是太伟大了。 所以借着这一章的思路,我很快有了本题的解题思路。给Trie树的每个节点增加一个pre属性,用来表示所有以从根节点到该节点构成的字符串为前缀的单词的个数。 题目已经提示我们了
提示三:在建立Trie树时同时进行统计!
所以我们在建立Trie树的时候,通过改造博文中的insert函数,我们每插入一个单词,该单词遍历过的节点的pre值都加1。这样,当我们要查找以字符串s为前缀的单词个数时,只要查找到该字符串s的节点,节点的pre即为以s为前缀的单词的个数。具体的代码实现请看下面: [cpp] #include<iostream> #include<string> #include<cstdlib> using namespace std; const int MAX_C=26; typedef struct Tri_Node { int pre;//以“从根节点到该节点构成的字符串”为前缀的单词的个数 struct Tri_Node *next[MAX_C]; }Trie; //初始化一棵树 void init_Trie(Trie** t)//二级指针 { *t=(Trie*)malloc(sizeof(Trie)); (*t)->pre=0;//参数用了二级指针,这样才将修改的pre的值传出去 for(int i=0;i<MAX_C;i++) { (*t)->next[i]=NULL; } } //将字符串s插入到树中 void insert_node(Trie* root,const string s) { if(root==NULL||s=="") return; int s_size=s.size(); Trie *p=root; for(int i=0;i<s_size;i++) { if(p->next[s[i]-‘a’]==NULL) { Trie *tmp=NULL; init_Trie(&tmp); tmp->pre++; p->next[s[i]-‘a’]=tmp; p=p->next[s[i]-‘a’]; } else { p=p->next[s[i]-‘a’]; p->pre++; } } } //查找以s为前缀的单词的个数 int search_pre(Trie* root, const string s) { int s_size=s.size(); Trie* p=root; int i=0; int rs=0; for(i=0;i<s_size;i++) { if(p->next[s[i]-‘a’]!=NULL) { p=p->next[s[i]-‘a’]; rs=p->pre; } else break; } if(i==s_size) return rs; else return 0; } int main() { int n,m; cin>>n; string s; Trie* root=NULL; init_Trie(&root); while(n–) { cin>>s; insert_node(root,s); } cin>>m; while(m–) { cin>>s; cout<<search_pre(root,s)<<endl; } return 0; } [/cpp] 该代码提交的结果:AC,用时1728ms,内存67MB。 由于对C语言及其指针不熟,中间还出现过一些小错误,比如init_Trie(Trie** t);的参数需要使用二级指针才能将值传出去;malloc需要cstdlib头文件等。]]>