My C++ solution of wordPattern, someone have better solution?


  • 0
    Y
    bool wordPattern(string pattern, string str) {
            unordered_map<char, string> hashtbl;
            unordered_map<string, char> hashtbl2;
            string::iterator it = pattern.begin();
            stringstream ss(str);
            string item;
            while (*it) {
                if(!getline(ss, item, ' '))
                    return false;
                if(hashtbl.find(*it) == hashtbl.end()&&hashtbl2.find(item)==hashtbl2.end()){
                    hashtbl[*it] = item;
                    hashtbl2[item]= *it;
                }
                else{
                    if (hashtbl.find(*it)!=hashtbl.end()&&hashtbl.at(*it) != item) {
                        return false;
    
                    }
                    if(hashtbl2.find(item)!=hashtbl2.end()&&hashtbl2.at(item)!=*it){
                        return false;
                    }
                }
                ++it;
            }
            if (getline(ss, item, ' '))
                return false;
            return true;
        }

  • 0
    Y
        // Little improvement than previous solution:
        bool wordPattern(string pattern, string str) {
            unordered_map<char, string> map1;
            unordered_map<string, char> map2;
            stringstream ss(str);
            string word;
            for (auto& c : pattern) {
                if (!std::getline(ss, word, ' ')) {
                    return false;
                }
                if (map1.find(c) != map1.end() && map1[c] != word
                 || map2.find(word) != map2.end() && map2[word] != c) {
                    return false;
                }
                map1[c] = word;
                map2[word] = c;
            }
            return !std::getline(ss, word, ' ');
        }

Log in to reply
 

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