leetcode刷題,總結,記錄,備忘 290
阿新 • • 發佈:2019-02-10
leetcode290 Word Pattern
Given a pattern
and a string str
,
find if str
follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern
and
a non-empty word in str
.
Examples:
- pattern =
"abba"
, str ="dog cat cat dog"
should return true. - pattern =
"abba"
"dog cat cat fish"
should return false. - pattern =
"aaaa"
, str ="dog cat cat dog"
should return false. - pattern =
"abba"
, str ="dog dog dog dog"
should return false.
Notes:
You may assume pattern
contains only lowercase letters, and str
contains
lowercase letters separated by a single space.
class Solution { public: bool wordPattern(string pattern, string str) { vector<string> vs; while (1) { int pos = str.find(" "); if (pos == string::npos) { vs.push_back(str); break; } else { vs.push_back(str.substr(0, pos)); str = str.substr(pos + 1); } } if (vs.size() != pattern.size()) { return false; } map<string, string> ms; map<string, string> ms2; for (int i = 0; i < pattern.size(); ++i) { string t; t += pattern[i]; if (ms.find(t) == ms.end() && ms2.find(vs[i]) == ms2.end()) { ms[t] = vs[i]; ms2[vs[i]] = t; } else { if (ms[t] != vs[i] || ms2[vs[i]] != t) { return false; } } } return true; } };