Problem:
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.
Summary:
判断所给字符串str中单词的形式与pattern中是否相符。
Solution:
以key为pattern中的char,value为str中的单词构成Hash Table,每加进一个新单词,判断原来若存在相同key的单词是否与新单词相同。
最终需排除不同key,value相同的情况。
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> s;
unordered_map<char, string> m; int flag = ;
for (int i = ; i < str.size(); i++) {
if (str[i] == ' ') {
s.push_back(str.substr(flag, i - flag));
flag = i + ;
}
}
s.push_back(str.substr(flag, str.size() - flag)); if (pattern.size() != s.size()) {
return false;
} for (int i = ; i < pattern.size(); i++) {
if (m[pattern[i]] == "") {
m[pattern[i]] = s[i];
}
else if (m[pattern[i]] != s[i]){
return false;
}
} for (unordered_map<char, string>::iterator i = m.begin(); i != m.end(); i++) {
for (unordered_map<char, string>::iterator j = m.begin(); j != m.end(); j++) {
if (i->second == j->second && i->first != j->first) {
return false;
}
}
} return true;
}
};