# 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].

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

# hihoCoder 1551-合并子目录

hihoCoder 1551-合并子目录

### 输出

3
/hihocoder/offer22/solutions/p1
/hihocoder/challenge30/p1/test
/game/moba/dota2/uninstall

8

# 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

# 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.

# LeetCode 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")
search("b..") -> true


Note:
You may assume that all words are consist of lowercase letters a-z.

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. */
{
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);
}
};

# 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.

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

# 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