程式語言 - LeetCode - C++ - 290. Word Pattern



參考資訊:
https://www.cnblogs.com/grandyang/p/4857022.html

題目:


解答:

class Solution {
public:
    bool wordPattern(string pattern, string s) {
        string w;
        vector<string> wd;
        stringstream ss(s);

        while (ss >> w) {
            wd.push_back(w);
        }

        if (pattern.size() != wd.size()) {
            return false;
        }

        unordered_map<char, string> mp1;
        unordered_map<string, char> mp2;

        for (int i = 0; i < pattern.size(); ++i) {
            char ch = pattern[i];
            w = wd[i];

            if (mp1.count(ch) && mp1[ch] != w) {
                return false;
            }
            if (mp2.count(w) && mp2[w] != ch) {
                return false;
            }

            mp1[ch] = w;
            mp2[w] = ch;
        }

        return true;
    }
};