My concise c++ solution by two maps and XOR manipulation


  • 0
    X
    class Solution {
    public:
        bool wordPattern(string pattern, string str)
        {
            vector<string> strs;
            string tmp;
            for(stringstream ss(str);ss>>tmp;strs.push_back(tmp));
            if(pattern.size()!=strs.size())
                return false;
            unordered_map<char,string> charStr;
            unordered_map<string,char> strChar;
            for(int i=0;i<pattern.size();i++)
            {
                if(!charStr.count(pattern[i])&&!strChar.count(strs[i]))
                    charStr[pattern[i]]=strs[i],strChar[strs[i]]=pattern[i];
                else if(charStr.count(pattern[i])^strChar.count(strs[i])||charStr[pattern[i]]!=strs[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.