Leetcode 290. Word Pattern
2018-09-10 本文已影响2人
SnailTyan
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Word Pattern2. Solution
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> strs;
split(str, strs);
if(pattern.size() != strs.size()) {
return false;
}
unordered_map<char, string> m1;
unordered_map<string, char> m2;
for(int i = 0; i < pattern.length(); i++) {
if(m1.find(pattern[i]) == m1.end()) {
m1[pattern[i]] = strs[i];
}
else if(m1[pattern[i]] != strs[i]) {
return false;
}
if(m2.find(strs[i]) == m2.end()) {
m2[strs[i]] = pattern[i];
}
else if(m2[strs[i]] != pattern[i]) {
return false;
}
}
return true;
}
private:
void split(string& str, vector<string>& strs) {
int start = 0;
for(int i = 0; i < str.length(); i++) {
if(str[i] == ' ') {
strs.push_back(str.substr(start, i - start));
start = i + 1;
}
}
strs.push_back(str.substr(start, str.length() - start));
}
};