My C++ 0ms solution


  • 0
    W
    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            unordered_map<char, string> recordc2s;
            unordered_map<string, char> records2c;
            stringstream ss;
            ss << str;
            string str_in;
            int patternIdx = 0;
            int wordCount = 0;
            while(patternIdx < pattern.size() && ss >> str_in){
            
                char patt = pattern[patternIdx];
                if(recordc2s.find(patt) == recordc2s.end()){
                    recordc2s.insert({patt, str_in});
                } else if(recordc2s[patt] != str_in){
                    return false;
                }
                
                if(records2c.find(str_in) == records2c.end()){
                    records2c.insert({str_in, patt});
                } else if(records2c[str_in] != patt){
                    return false;
                }
                
                patternIdx ++;
                wordCount ++;
            }
            
            while(ss >> str){
                wordCount++;
            }
            
            if(wordCount != pattern.size()){
                return false;
            } else {
                return true;
            }
            
        }
    };

Log in to reply
 

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