C++ using One unordered_set and One vector


  • 0
    H
    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            vector<string> words;
            unordered_set<string>  strset;
            vector<int> pat(26,-1);
            istringstream ss(str);
            string single;
            for(int i = 0;i<pattern.size();i++){
                ss>>single;
                if(single.empty())
                    return false;
                if(pat[pattern[i]-'a'] !=-1&&words[pat[pattern[i]-'a']].compare(single)!=0)
                    return false;
                else if(pat[pattern[i]-'a'] ==-1&&strset.find(single)!=strset.end())
                    return false;
                pat[pattern[i]-'a'] = i;
                words.push_back(single);
                strset.insert(single);
            }
            if(!ss.eof())
                return false;
            return true;
        }
    };

Log in to reply
 

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