Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

290. Word Pattern 🌟

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.

Hashmap Solution

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();
    }
};