[LeetCode] Word Pattern
阿新 • • 發佈:2017-10-17
tco logs sum pub same char cas 三種 false
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"
, str ="dog cat cat fish"
- 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.
給定一個模式串pattern和一個字符串str,找到如果str是否遵循相同的模式。
使用了map、set、vector三種容器。利用map來存儲模式串字符與字符串中字符串的對應關系,利用set的性質來檢測pattern與str中的對應元素是否一一對應,利用vector存儲str中去除空格後的每一個單詞。
最後用map中模板的值構建新的字符串觀察是否與給定的str相等。
總的來說是一個分離+重構+比較的過程。
class Solution { public: bool wordPattern(string pattern, string str) { istringstream istr(str); string s; vector<string> svec; while (istr >> s) svec.push_back(s); if (pattern.size() != svec.size()) return false; unordered_map<char, string> c2s; unordered_set<char> cs; unordered_set<string> ss(svec.begin(), svec.end()); for (char c : pattern) cs.insert(c); if (cs.size() != ss.size()) return false; for (int i = 0; i != pattern.size(); i++) { c2s[pattern[i]] = svec[i]; } string tmp; for (auto c : pattern) { tmp += (c2s[c] + " "); } if (tmp != str + " ") return false; return true; } }; // 0 ms
[LeetCode] Word Pattern