0ms c++ solution using map, is there a simple one?


  • 1
    L
    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
             map<char,string> strmap;
             map<string,char> patmap;
             stringstream ss(str);
             string tmp;
             int i;
             for(i=0;(ss>>tmp);++i)
             {
                 if(strmap.find(pattern[i])!=strmap.end()){
                     if (strmap[pattern[i]]!=tmp)
                        return false;
                 }
                 else
                     strmap[pattern[i]]=tmp;
                 if(patmap.find(tmp)!=patmap.end()){
                     if (patmap[tmp]!=pattern[i])
                        return false;
                 }
                 else
                    patmap[tmp]=pattern[i];
             }
             if(pattern.length()!=i) return false;
        }
    };
    

    I guess the two if-else is not neccesary. But I don't know how to simplify it.?


  • 0
    Z

    Hi, can you explain a little bit about what does "ss>>temp" means here?? thanks


  • 0
    L

    it means transfer a word each time from ss to temp and test if ss is empty meantime


  • 0
    4

    Excuse me, would you please tell me why you don't return true? I don't see any part of the code return true, but it's accept.


Log in to reply
 

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