题目链接:https://leetcode.com/problems/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:
"abba"
, str = "dog cat cat dog"
should return true."abba"
, str = "dog cat cat fish"
should return false."aaaa"
, str = "dog cat cat dog"
should return false."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.
思路:对这题,我也是感觉哔了狗了,无限WA,唉!本来想做几个水题的,又被虐了一顿。这道题是要求一一对应的关系,也就是说一个pattern对应一个str的子串,同时一个str的子串也要对应pattern的一个字母
代码如下:
class Solution { public: bool wordPattern(string pattern, string str) { unordered_map<char, string> hash; unordered_map<string, char> hashR; vector<string> vec; int i = 0; while(i < str.size())//分割字符串,蛋疼啊,为何c++标准为什么还没有提供函数分割,连java都有^.^ { size_t pos = str.find(' ', i); vec.push_back(str.substr(i, pos - i)); if(pos == string::npos) break; i = pos+1; } if(pattern.size() != vec.size())//如果模型和字符串个数不一样,则不匹配 return false; for(int i = 0; i< pattern.size(); i++) { if((hash.find(pattern[i]) == hash.end() && hashR.find(vec[i]) == hashR.end())//如果原来不存在 || (hash[pattern[i]] == vec[i] && hashR[vec[i]] == pattern[i]))//原来存在,并且和现在对应关系相同 { hash[pattern[i]] = vec[i]; hashR[vec[i]] = pattern[i]; } else return false; } return true; } };