C++ 4ms solution, straight but not so neat


  • 0
    D
    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            map<char,string> dict;
            map<string, int> uniqCnt;
            vector<string> wordList;
            string buf;
            
            stringstream ss(str);
            while(ss>>buf)
                wordList.push_back(buf);
                
            if(wordList.size()!=pattern.size())
                return false;
                
            map<char,string>::iterator it;
            map<string, int>::iterator it1;
        
            for(int i=0;i<pattern.size();i++)
                {
                it=dict.find(pattern[i]);
                if(it==dict.end())
                    dict[pattern[i]]=wordList[i];
                else
                    if(dict[pattern[i]]==wordList[i])
                        continue;
                    else
                        return false;
                }
                
            for(it=dict.begin();it!=dict.end();it++)
                uniqCnt[it->second]++;
                
            for(it1=uniqCnt.begin();it1!=uniqCnt.end();it1++)
                if(it1->second>1)
                    return false;
            return true;
        }
    };

Log in to reply
 

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