forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
87 lines (68 loc) · 1.97 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/// Source : https://leetcode.com/problems/replace-words/description/
/// Author : liuyubobobo
/// Time : 2017-11-06
#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
using namespace std;
/// Hash Set + Brute Force
/// Time Complexity: O(len(words) * O(w)^2)
/// Space Complexity: O(len(dict))
class Solution {
private:
unordered_set<string> roots;
public:
string replaceWords(vector<string>& dict, string sentence) {
for(string root: dict)
roots.insert(root);
vector<string> words = split(sentence, ' ');
// for(string word: words)
// cout << word << " ";
// cout << endl;
vector<string> res;
for(string word: words)
res.push_back(getRoot(word));
return join(res, ' ');
}
private:
string getRoot(const string& word){
for(int i = 1; i <= word.size() ; i ++)
if(roots.find(word.substr(0, i)) != roots.end())
return word.substr(0, i);
return word;
}
vector<string> split(const string& s, char delimiter){
vector<string> res;
size_t i = 0;
while(i < s.size()){
size_t pos = s.find(delimiter, i);
if(pos == string::npos){
res.push_back(s.substr(i));
break;
}
else{
res.push_back(s.substr(i, pos-i));
i = pos + 1;
}
}
return res;
}
string join(const vector<string>& vec, char delimiter){
if(vec.size() == 0)
return "";
string ret = vec[0];
for(int i = 1 ; i < vec.size() ; i ++)
ret += (delimiter + vec[i]);
return ret;
}
};
int main() {
vector<string> dict;
dict.push_back("cat");
dict.push_back("bat");
dict.push_back("rat");
string sentence = "the cattle was rattled by the battery";
cout << Solution().replaceWords(dict, sentence) << endl;
return 0;
}