Posted on

Description

Submission

class Solution {
public:
    bool wordPattern(string pattern, string str) {
        map<char, string> m1;
        map<string, char> m2;
        int beg = 0, end = 0;
        int word_count = 0;
        for(int i = -1; end < str.size() + 1; ++end) {
            if (str[end] == ' ' || end == str.size()) {
                word_count++;
                string word = str.substr(beg, end - beg);
                auto iter1 = m1.find(pattern[++i]);
                if (iter1 == m1.end()) {
                    m1.insert(make_pair(pattern[i], word));
                } else {
                    if (iter1->second != word) {
                        return false;
                    }
                }

                auto iter2 = m2.find(word);
                if (iter2 == m2.end()) {
                    m2.insert(make_pair(word, pattern[i]));
                } else {
                    if (iter2->second != pattern[i]) {
                        return false;
                    }
                }

                beg = end + 1;

            }

        }
        return word_count == pattern.length();
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *