Categories:

Tags:



Problem

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.

Constraints

  • 1 <= pattern.length <= 300
  • pattern contains only lower-case English letters.
  • 1 <= s.length <= 3000
  • s contains only lowercase English letters and spaces ' '.
  • s does not contain any leading or trailing spaces.
  • All the words in s are separated by a single space.

Solution

The problem Word Pattern can be solved by spliting given string and checking for a full match using 2 hash maps.

Implementation

class Solution
{
  public:
    bool wordPattern(string pattern, string s)
    {
        vector<string> word;

        int start = 0, end;
        do
        {
            end = s.find(' ', start);
            word.push_back(s.substr(start, end - start));
            start = end + 1;
        } while (end != -1);

        if (pattern.length() != word.size())
            return false;

        unordered_map<char, string> p2w;
        unordered_map<string, char> w2p;

        for (int i = 0; i < pattern.length(); i++)
        {
            if (p2w.find(pattern[i]) == p2w.end() && w2p.find(word[i]) == w2p.end())
            {
                p2w[pattern[i]] = word[i];
                w2p[word[i]] = pattern[i];
            }
            else if (p2w[pattern[i]] != word[i] || w2p[word[i]] != pattern[i])
                return false;
        }

        return true;
    }
};