什麼是前綴樹、前綴樹的基本特徵、前綴樹的應用、
所謂的字典樹又被稱爲前綴樹或者叫做trie樹,是處理字符串的常用數據結構。其優點是利用字符串的公共前綴來
節約存儲空間。其基本性質如下:
(1)根節點沒有字符路徑。除根節點之外,每一個節點都被一個字符路徑找到。
(2)從根節點出發到任何一個節點,如果將沿途 的字符連接起來,一定是某個字符串的前綴。
(3)每個節點向下所有的字符路徑上的字符都不同。
實現一個 Trie,包含 insert, search, 和 startsWith 這三個方法。
class TrieNode
{
public:
int path;
int ends;
unordered_map<char, TrieNode *> m;//delete單詞
};
class Trie {
public:
TrieNode * root;
Trie() {
root = new TrieNode();//頭節點
// do intialization if necessary
}
/*
* @param word: a word
* @return: nothing
*/
void insert(string &word) {
// write your code here
TrieNode *head = root;
for (int i = 0; i < word.size(); i++) {
/* code */
if(head->m.count(word[i]) == 1)
{
head = head->m[word[i]];
head->path++;
if(i == word.size() - 1 )
head->ends++;
}
else
{
TrieNode *node = new TrieNode();
node->path = 1;
if(i == word.size() - 1 )
node->ends++;
else
node->ends = 0;
head->m[word[i]] = node;
head = node;
}
}
}
/*
* @param word: A string
* @return: if the word is in the trie.
*/
bool search(string &word) {
// write your code here
TrieNode *head = root;
for (int i = 0; i < word.size(); i++) {
/* code */
if(head->m.count(word[i])== 1)
{
head = head->m[word[i]];
}
else
{
return false;
}
}
if(head->ends >=1)
{
return true;
}
else
return false;
}
/*
* @param prefix: A string
* @return: if there is any word in the trie that starts with the given prefix.
*/
bool startsWith(string &prefix) {
// write your code here
TrieNode *head = root;
for (int i = 0; i < prefix.size(); i++) {
/* code */
if(head->m.count(prefix[i] )== 1)
{
head = head->m[prefix[i]];
}
else
{
return false;
}
}
return true;
}
};
n 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.
Example 1:
Input: dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
You need to output the sentence after the replacement.
The input will only have lower-case letters.
1 <= dict words number <= 1000
1 <= sentence words number <= 1000
1 <= root length <= 100
1 <= sentence words length <= 1000
class TrieNode
{
public:
int path;
int ends;
unordered_map<char, TrieNode *> m;//delete單詞
};
class Trie {
public:
int index = 0;
TrieNode * root;
Trie() {
root = new TrieNode();//頭節點
// do intialization if necessary
}
/*
* @param word: a word
* @return: nothing
*/
void insert(string &word) {
// write your code here
TrieNode *head = root;
for (int i = 0; i < word.size(); i++) {
/* code */
if(head->m.count(word[i]) == 1)
{
head = head->m[word[i]];
head->path++;
if(i == word.size() - 1 )
head->ends++;
}
else
{
TrieNode *node = new TrieNode();
node->path = 1;
if(i == word.size() - 1 )
node->ends++;
else
node->ends = 0;
head->m[word[i]] = node;
head = node;
}
}
}
/*
* @param word: A string
* @return: if the word is in the trie.
*/
bool search(string &word) {
// write your code here
TrieNode *head = root;
for (int i = 0; i < word.size(); i++) {
/* code */
if(head->m.count(word[i]) == 1)
{
head = head->m[word[i]];//如果當前字符是結尾的話
}
else
{
return false;
}
}
if(head->ends >=1)
{
return true;
}
else
return false;
}
/*
* @param word: A string
* @return: if the word is in the trie.
*/
bool isWord(string &word) {
// write your code here
TrieNode *head = root;
for (int i = 0; i < word.size(); i++) {
/* code */
if(head->m.count(word[i]) == 1)
{
head = head->m[word[i]];//如果當前字符是結尾的話
if(head->ends >=1)
{
index = i;
return true;//也就是說如果當前字符
}
}
else
{
return false;
}
}
if(head->ends >=1)
{
return true;
}
else
return false;
}
/*
* @param prefix: A string
* @return: if there is any word in the trie that starts with the given prefix.
*/
bool startsWith(string &prefix) {
// write your code here
TrieNode *head = root;
for (int i = 0; i < prefix.size(); i++) {
/* code */
if(head->m.count(prefix[i]) == 1)
{
head = head->m[prefix[i]];
}
else
{
return false;
}
}
return true;
}
//查找某個字符的前綴是
};
class Solution {
public:
string replaceWords(vector<string>& dict, string sentence)
{
vector<string>v = splitString(sentence);
string s ="";
Trie t;
for(int i = 0; i < dict.size(); i++)
{
t.insert(dict[i]);
}
for(int j = 0; j < v.size(); j++)
{
if(t.isWord(v[j]))
v[j] = v[j].substr(0,t.index+1);
}
for(int j = 0; j < v.size()-1; j++)
s+= v[j]+" ";
s+=v[v.size() -1];
return s;
}
vector<string> splitString(string str)
{
string ::size_type pos1 = 0,pos2 = 0;
vector<string> res;
while (str.find(" ",pos1) != string::npos) {
pos2 = str.find(" ",pos1);//找到要查找的字符串
res.push_back(str.substr(pos1, pos2 - pos1));
pos1 = pos2+1;
}
if (pos1 != str.size()) {
res.push_back(str.substr(pos1));
}
return res;
}
};
//暴力解法
class Solution {
public:
string replaceWords(vector<string>& dict, string sentence)
{
vector<string>v = splitString(sentence);
string s ="";
for(int i = 0; i < dict.size(); i++)
{
for(int j = 0; j < v.size(); j++)
{
if(v[j].substr(0, dict[i].size()) == dict[i])//字符串截取操縱
{
v[j] = dict[i];
}
}
}
for(int j = 0; j < v.size()-1; j++)
s+= v[j]+" ";
s+=v[v.size() -1];
return s;
}
vector<string> splitString(string str)
{
string ::size_type pos1 = 0,pos2 = 0;
vector<string> res;
while (str.find(" ",pos1) != string::npos) {
pos2 = str.find(" ",pos1);//找到要查找的字符串
res.push_back(str.substr(pos1, pos2 - pos1));
pos1 = pos2+1;
}
if (pos1 != str.size()) {
res.push_back(str.substr(pos1));
}
return res;
}
};
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.
class TrieNode
{
public:
int path;
int ends;
unordered_map<char, TrieNode *> m;//delete單詞
};
class WordDictionary {
public:
TrieNode * root;
/** Initialize your data structure here. */
WordDictionary()
{
root = new TrieNode();//頭節點
}
/** Adds a word into the data structure. */
void addWord(string word)
{
TrieNode *head = root;
for (int i = 0; i < word.size(); i++) {
/* code */
if(head->m.count(word[i]) == 1)
{
head = head->m[word[i]];
head->path++;
if(i == word.size() - 1 )
head->ends++;
}
else
{
TrieNode *node = new TrieNode();
node->path = 1;
if(i == word.size() - 1 )
{
node->ends++;
}
else
node->ends = 0;
head->m[word[i]] = node;
head = node;
}
}
//cout <<"OK " <<endl;
}
/** 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)
{
TrieNode *head = root;
return proccess(word, 0, head);
}
bool proccess(string word, int i , TrieNode *head)
{
if(i == word.size())//最後一個字符
{
if(head->ends>=1)
return true;
else
return false;
}
if(word[i] == '.')
{
for(int mm = 0; mm < 26; mm++)
{
// cout << "mm" << mm<<endl;
TrieNode *h = head;
if(h->m.count('a'+mm) == 1)
{
h = head->m['a'+mm];//下面怎麼走呢
if(proccess( word, i+1 , h))
return true;
}
}
return false;
}
else
{
if(head->m.count(word[i])== 1)
{
head = head->m[word[i]];
return proccess(word, i+1, head);//head是當前節點 當到達s.size() -1 的時
//候,head正好指向最後一個
//字符
}
else
return false;
}
return true;
}
};
/************************************************************************/
/*
分金條問題
一塊金條切成兩半,是需要花費和長度數值一樣的銅板的。比如 長度爲20的 金條,不管切成長度多大的兩半,
都要花費20個銅 板。一羣人想整分整塊金 條,怎麼分最省銅板? 例如,給定數組{10,20,30},代表一共三個人,
整塊金條長度爲 10+20+30=60. 金條要分成10,20,30三個部分。 如果, 先把長 度60的金條分成10和50,
花費60 再把長度50的金條分成20和30, 花費50 一共花費110銅板。 但是如果, 先把長度60的金條分成30
和30,花費60 再把長度30 金條分成10和20,花費30 一共花費90銅板。 輸入一個數組,返回分割的最小代價。
*/
/************************************************************************/
/************************************************************************/
/* 算法思想:
要實現這個目標 :要利用哈夫曼編碼 編碼長度越短,代價越低
*/
/************************************************************************/
class Less_Money
{
public:
priority_queue<int,vector<int>,greater<int>> p;//小頂堆 默認是大頂堆
int getMin(vector<int> arr)
{
int sum = 0;
int cur = 0;
for (int i = 0; i < arr.size(); i++)
{
p.push(arr[i]);
}
while (p.size()>1)
{
int first = p.top();
p.pop();
int second = p.top();
p.pop();
cur = first + second;
cout <<"first: "<<first << " second: "<< second<<endl;
sum += cur ;
p.push(cur);
}
return sum;
}
};
我們有如下工作:difficulty[i]是第i個工作的難度,profit[i]是第i個工作的利潤。
現在我們有一些工人。 worker[i]是第i個工人的能力,這意味着這個工人最多完成難度爲worker[i]的工作。
每個工人最多隻能分配一份工作,但一份工作可以多次完成。
例如,如果3個人嘗試完成1美元的相同工作,那麼總利潤將爲3美元。 如果工人無法完成任何工作,他的利潤爲0美元。
我們可以獲得的利潤最大是多少?
樣例
樣例 1:
輸入: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
輸出: 100
解釋: 工人們分別被分配工作難度 [4,4,6,6],他們各自取得的利潤爲 [20,20,30,30].
注意事項
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i],profit[i],worker[i]在[1,10 ^ 5]範圍內
class Work
{
public:
int difficulty;
int profit;
Work(int d, int p)
{
this->difficulty = d;
this->profit = p;
}
};//
bool operator<(Work w1, Work w2)
{
return w1.profit < w2.profit;
}
class Solution {
public:
/**
* @param difficulty:
* @param profit:
* @param worker:
* @return: nothing
*/
priority_queue<Work> p;
int maxProfitAssignment(vector<int> &difficulty, vector<int> &profit, vector<int> &worker)
{
for (int i = 0; i < profit.size(); i++)
{
p.push(Work(difficulty[i],profit[i]));
}
sort(worker.begin(), worker.end(),greater<int>());
int index = 0;
int sum = 0;
while (!p.empty() && index <worker.size()) {
Work w = p.top();
if(w.difficulty <= worker[index])
{
sum +=w.profit;//
index++;
}
else
{
p.pop();
}
}
return sum;
}
};
數字是不斷進入數組的,在每次添加一個新的數進入數組的同時返回當前新數組的中位數。
樣例
樣例1
輸入: [1,2,3,4,5]
輸出: [1,1,2,2,3]
樣例說明:
[1] 和 [1,2] 的中位數是 1.
[1,2,3] 和 [1,2,3,4] 的中位數是 2.
[1,2,3,4,5] 的中位數是 3.
樣例2
輸入: [4,5,1,3,2,6,0]
輸出: [4,4,4,3,3,3,3]
樣例說明:
[4], [4,5] 和 [4,5,1] 的中位數是 4.
[4,5,1,3], [4,5,1,3,2], [4,5,1,3,2,6] 和 [4,5,1,3,2,6,0] 的中位數是 3.
挑戰
時間複雜度爲O(nlogn)
說明
中位數的定義:
這裏的中位數不等同於數學定義裏的中位數。
A[(n−1)/2]。
比如:數組A=[1,2,3]的中位數是2,數組A=[1,19]的中位數是1。
輸入測試數據 (每行一個參數)
如何理解測試數據?
class Solution {
public:
/**
* @param nums: A list of integers
* @return: the median of numbers
*/
priority_queue<int,vector<int>, greater<int>> pMin;
priority_queue<int,vector<int>, less<int>> pMax;
//使用大頂堆來保存左邊的數據,使用小頂堆保存右邊的數據
vector<int> medianII(vector<int> &nums) { //分金條問題
// write your code here
//特殊處理
vector<int> res;
for (int i = 0; i < nums.size(); i++)
{
/* code */
if(pMax.empty())
pMax.push(nums[i]);
else
{
if(nums[i] > pMax.top())//關鍵步驟
pMin.push(nums[i]);
else
pMax.push(nums[i]);
}
int l = pMax.size();
int r = pMin.size();
if(l - r ==2)
{
int t = pMax.top();
pMax.pop();
pMin.push(t);
}
if(r - l ==2)
{
int t = pMin.top();
pMin.pop();
pMax.push(t);
}
l = pMax.size();
r = pMin.size();
if(l-r == 0)
{
res.push_back(pMax.top());
}
else if(l-r == 1)
res.push_back(pMax.top());
else
res.push_back(pMin.top());
}
return res;
}
};
一些項目要佔用一個會議室宣講,會議室不能同時容納兩個項目 的宣講。 給你每一個項目開始的時間和結束的時
間(給你一個數 組,裏面 是一個個具體的項目),你來安排宣講的日程,要求會 議室進行 的宣講的場次最多。
返回這個最多的宣講場次。
給定一個字符串類型的數組strs,找到一種拼接方式,使得把所 有字 符串拼起來之後形成的字符串具有最低的
字典序。
bool compare(string s1, string s2)
{
return s1+s2 < s2+s1;
}
class Solution
{
public:
string getMinStr(vector<string> arr)
{
sort(arr.begin(), arr.end(),compare);
string res ="";
for (int i = 0; i < arr.size(); i++)
{
res +=arr[i];
}
return res;
}
};