Word Pattern 词语模式
Given a pattern
and a string str
, find if str
follows the same pattern.
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:
- Both
pattern
andstr
contains only lowercase alphabetical letters. - Both
pattern
andstr
do not have leading or trailing spaces. - Each word in
str
is separated by a single space. - Each letter in
pattern
must map to a word with length that is at least 1.
class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, int> m1;
unordered_map<string, int> m2;
istringstream in(str);
int i = 0;
for (string word; in >> word; ++i) {
if (m1.find(pattern[i]) != m1.end() || m2.find(word) != m2.end()) {
if (m1[pattern[i]] != m2[word]) return false;
} else {
m1[pattern[i]] = m2[word] = i + 1;
}
}
return i == pattern.size();
}
};