class Solution {
public:
bool wordPattern(string pattern, string s) {
unordered_map<char, string> Map;
unordered_set<string> mapped;
int m = pattern.size();
int n = s.size();
int idx = 0;
int pIdx = 0;
while (idx < n) {
string str = "";
while (idx < n && s[idx] != ' ') str.push_back(s[idx++]);
if (Map.count(pattern[pIdx])) {
if (Map[pattern[pIdx]] != str) return false;
} else {
if (mapped.count(str)) return false;
mapped.insert(str);
Map[pattern[pIdx]] = str;
}
idx += 1;
pIdx += 1;
}
return pIdx == m;
}
};
Time Complexity: O(n)
Space: O(m)
拿來做為 map 的基礎題還不錯