🎉 One-stop destination for all your technical interview Preparation 🎉
Given a pattern and a string s, find if s 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 s.
i
with 0 to count words in given string.false
.false
.i==pattern.size()
, i.e. count of words in string and pattern same or not.class Solution {
public:
bool wordPattern(string pattern, string s)
{
unordered_map<char, string> mp;
unordered_map<string, char> mp2;
stringstream ss(s);
string word;
int i = 0;
while (ss >> word) {
if (mp.count(pattern[i]) == 0) {
if (mp2.count(word) == 0) {
mp[pattern[i]] = word;
mp2[word] = pattern[i];
i++;
} else {
return false;
}
} else {
if (mp[pattern[i]] != word) {
return false;
}
i++;
}
}
return i == pattern.size();
}
};