[LeetCode] Word Pattern
Posted immjc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 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"
, str ="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.
给定一个模式串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的主要内容,如果未能解决你的问题,请参考以下文章