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 inpattern
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.
注意要双向检查,一一对应,不能重复。
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> patternMap(26, "");
unordered_set<string> wordSet;
int strStartPos = 0;
int strEndPos = 0;
int patternIdx = 0;
for (; patternIdx < pattern.size() && strEndPos != string::npos; ++patternIdx) {
string word;
strEndPos = str.find(' ', strStartPos);
if (strEndPos == string::npos) {
word = str.substr(strStartPos);
}
else {
word = str.substr(strStartPos, strEndPos - strStartPos);
strStartPos = strEndPos + 1;
}
if (patternMap[pattern[patternIdx] - 'a'].empty()) {
if (wordSet.find(word) == wordSet.end()) {
patternMap[pattern[patternIdx] - 'a'] = word;
wordSet.emplace(word);
}
else {
return false;
}
}
else {
if (patternMap[pattern[patternIdx] - 'a'] != word) {
return false;
}
}
}
return (patternIdx == pattern.size() && strEndPos == string::npos);
}
};