C++ solution with two maps


  • 0
    L

    class Solution {
    public:

    bool wordPattern(string pattern, string str) {
        map<char, string> p2str;
        map<string, char> str2p;
        vector<string> vs;
        string s;
        if(find(str.begin(), str.end(), ' ') == str.end())
            vs.push_back(str);
        else
        {
            for(auto c: str)
            {
                if(c != ' ')
                    s += c;
                else
                {
                    vs.push_back(s);
                    s = "";
                }
            }
            vs.push_back(s);
        }
        if(pattern.length() != vs.size())
            return false;
        
        for(int i = 0; i < pattern.length(); i++)
        {
            auto iter1 = p2str.find(pattern[i]);
            auto iter2 = str2p.find(vs[i]);
            if(iter1 == p2str.end())
            {
                if(iter2 != str2p.end())
                    return false;
                else
                {
                    p2str[pattern[i]] = vs[i];
                    str2p[vs[i]] = pattern[i];
                }
            }
            else
            {
                if(iter1->second != vs[i])
                    return false;
            }
        }
        return true;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.