My c++ solution with two unordered_map and istringstream


  • 3
    J
    bool wordPattern(string pattern, string str) {
        string tmp;
        vector<string> strvec;
        istringstream isstream(str);
        unordered_map<char, string> m1;
        unordered_map<string, char> m2;
        
        while(isstream >> tmp){
            strvec.push_back(tmp);
        }
        
        if(pattern.size() != strvec.size()){
            return false;
        }
        
        for(int i =0; i < pattern.size(); ++i){
            if(m1.find(pattern[i]) != m1.end()){
                if(m1[pattern[i]] != strvec[i]){
                    return false;
                }
            }
            else{
                m1[pattern[i]] = strvec[i];
            }
            
            if(m2.find(strvec[i]) != m2.end()){
                if(m2[strvec[i]] != pattern[i]){
                    return false;
                }
            }
            else{
                m2[strvec[i]] = pattern[i];
            }
        }
        return true;
    }

Log in to reply
 

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