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.
class Solution { public: bool wordPattern(string pattern, string str) { int i = 0; istringstream stream(str); unordered_map<char, string> chtostr; unordered_map<string, char> strtoch; string word; vector<string> str2; while (stream >> word) str2.push_back(word); if (pattern.size() != str2.size()) return false; for (; i < pattern.size(); i++) { auto findPtr = chtostr.find(pattern[i]); if (findPtr != chtostr.cend()) { if (findPtr->second != str2[i]) return false; } else chtostr.insert({ pattern[i], str2[i] }); } i = 0; for (; i < str2.size(); i++) { auto findPtr = strtoch.find(str2[i]); if (findPtr != strtoch.cend()) { if (findPtr->second != pattern[i]) return false; } else strtoch.insert({str2[i], pattern[i]}); } return true; } };
原文:http://www.cnblogs.com/dylqt/p/4887181.html