C++ simple solution


  • 0
    H
    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            unordered_map<char, string> um1;
            unordered_map<string, char> um2;
            stringstream ss(str);
            string tmp;
            for(auto c : pattern) {
                if(!(ss >> tmp)) return false;
                if(um1.find(c) == um1.end() && um2.find(tmp) == um2.end() ) {
                    um1[c] = tmp;
                    um2[tmp] = c;
                }
                if(um1[c] != tmp || um2[tmp] != c) return false;
            }
            if(!ss.eof()) return false;
            return true;
        }
    };
    
    

Log in to reply
 

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