Leetcode 290 Solution

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

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

Solution

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        int i = 0;
        map<char, string> a;
        map<string, char> r;

        int last_start = 0;
        int last_end = 0;

        for (int i = 0; i < pattern.size(); i++)
        {
            last_end = str.find_first_of(' ', last_start);
            auto v = str.substr(last_start, last_end == -1 ? str.length() - last_start : last_end - last_start);

            char ch = pattern[i];

            if (a.find(ch) == a.end())
                a[ch] = v;
            else if (a[ch] != v)
                return false;

            if (r.find(v) == r.end())
                r[v] = ch;
            else if (r[v] != ch)
                return false;

            if (last_end == -1 && i != pattern.size() - 1)
                return false;

            last_start = last_end + 1;
        }

        if (last_end != -1)
            return false;

        return true;
    }
};