← All problems

290. Word Pattern

EasyOpen on LeetCodeProblem statement

Problem Statement

290. Word Pattern

Easy


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.

 

Example 1:

Input: pattern = "abba", s = "dog cat cat dog"
Output: true

Example 2:

Input: pattern = "abba", s = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false

 

Constraints:

C++

Source file
class Solution {
public:
    bool wordPattern(string pattern, string s) {
        unordered_map <char, string> m;
        unordered_map <string, char> n;
        stringstream ss(s);
        int i=0;
        string word;
        while (ss >> word) {
            auto a = m.find(pattern[i]);
            auto str = n.find(word);
            if(a==m.end() && str==n.end()){             // new key
                m.insert({pattern[i], word});
                n.insert({word, pattern[i]});
            }
            else if((a!=m.end() && a->second!=word) || (str!=n.end() && str->second!=pattern[i]))
                return false;
            i++;
        }
        if(i!=pattern.length())                      // check if char-word count same
            return false;
        return true;
    }
};