C++ 0 ms very clean and easy to read


  • 6
    R
    bool wordPattern(string pattern, string str) 
    {
        istringstream ss(str);
        string word;
        unordered_map<char, string> bmap;
        unordered_map<string, char>rbmap;
        
        for (char c : pattern)
        {
            if (! (getline(ss, word, ' ')))
                return false;
            if ( bmap.emplace(c,word).first->second != word)
                return false;
            if (rbmap.emplace(word,c).first->second != c)
                return false;
        }
        return ! getline(ss, word, ' ');   
    }

  • 0
    Y
    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            istringstream stream(str);
            unordered_map<string, char> hash;
            unordered_map<char, string> reflect;
            int i = 0;
            while(i<pattern.length() && stream >> str) {
                if(hash.find(str)==end(hash) && reflect.find(pattern[i])==end(reflect)) {
                    hash[str] = pattern[i];
                    reflect[pattern[i]] = str;
                }else {
                    if(hash[str] != pattern[i])
                        return false;
                }
                ++i;
            }
            if(stream >> str || i!=pattern.length())
                return false;
            return true;
        }
    };
    

Log in to reply
 

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