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.
Credits:
Special thanks to @minglotus6 for adding this problem and creating all test cases.
1 class Solution { 2 public: 3 bool wordPattern(string pattern, string str) { 4 vector<string> dic; 5 istringstream sin(str); 6 string tmp; 7 while (sin >> tmp) dic.push_back(tmp); 8 if (dic.size() != pattern.size()) return false; 9 unordered_map<char, string> mp1; 10 unordered_map<string, char> mp2; 11 for (int i = 0; i < pattern.size(); ++i) { 12 if (mp1.find(pattern[i]) == mp1.end()) { 13 mp1[pattern[i]] = dic[i]; 14 } else if (mp1[pattern[i]] != dic[i]) { 15 return false; 16 } 17 if (mp2.find(dic[i]) == mp2.end()) { 18 mp2[dic[i]] = pattern[i]; 19 } else if (mp2[dic[i]] != pattern[i]) { 20 return false; 21 } 22 } 23 return true; 24 } 25 };