lc290-Word Pattern

学习一个如何split string。

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
class Solution {
unordered_map<char, string> mp;
set<string> words;
public:
bool wordPattern(string pattern, string str) {
int l = pattern.length();
stringstream ss;
ss.str(str);
string item;
vector<string> v;
while (getline(ss, item, ' ')) {
v.push_back(item);
}
if (l!=v.size()) return false;
for (int i = 0; i < l; i++) {
if (!mp.count(pattern[i])) {
if (words.find(v[i])!=words.end()) return false;
words.insert(v[i]);
mp[pattern[i]] = v[i];
}
else if (v[i]!=mp[pattern[i]]) return false;
}
return true;
}
};

或者:

1
2
3
4
5
6
stringstream ss(str);
string item;
vector<string> v;
while (ss>>item) {
v.push_back(item);
}