Leetcode 291 Solution

This article provides solution to leetcode question 291 (word-pattern-ii)

https://leetcode.com/problems/word-pattern-ii

Solution

class Solution {
    unordered_map<char, string> m;
    unordered_set<string> visited;

public:
    bool wordPatternMatch(const string& pattern, int i, const string& str, int j)
    {
        if (i == pattern.size() && j == str.size())
            return true;
        else if (i == pattern.size() || j == str.size())
            return false;

        auto pattern_ch = pattern[i];

        if (m.find(pattern_ch) == m.end())
        {
            for (int k = j; k < str.size(); k++)
            {
                auto ss = str.substr(j, k - j + 1);
                if (visited.find(ss) != visited.end())
                    continue;

                m[pattern_ch] = ss;
                visited.insert(ss);
                if (wordPatternMatch(pattern, i + 1, str, k + 1))
                    return true;
                m.erase(pattern_ch);
                visited.erase(ss);
            }
        }
        else
        {
            auto ss = m[pattern_ch];
            if (str.substr(j, ss.size()) != ss)
                return false;

            if (wordPatternMatch(pattern, i + 1, str, j + ss.size()))
                return true;
        }

        return false;
    }

    bool wordPatternMatch(string pattern, string str)
    {
        return wordPatternMatch(pattern, 0, str, 0);
    }
};