c++ 0ms two maps no stringstream


  • 0
    A
    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            int begin = 0, space = str.find(" ");
            if(space == string::npos && pattern.size() == 1)
                return true;
            else if(space == string::npos)
                return false;
            unordered_map<string, char> hashword;
            unordered_map<char, string> hashchar;            
            for(int i=0; i<pattern.size(); ++i){
                //REMEMBER: substr(pos, LENGTH)
                string word = str.substr(begin, space-begin);
                if(hashword[word] != pattern[i] && hashword[word] != 0)
                    return false;
                else if(hashchar[pattern[i]] != word && hashchar[pattern[i]] != "")
                    return false;
                hashword[word] = pattern[i];
                hashchar[pattern[i]] = word;
                begin = space+1;
                space = str.find(" ", begin+1);            
            }
            space = str.find_last_of(" ");
            return begin > space && space != string::npos? false: true;
        }
    };

Log in to reply
 

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