My long but clear cpp code, using set and unordered_map


  • 0
    C
    class Solution {
    public:
        
        vector<string> lex(const string &str)
        {
            vector<string> tokens;
            
            int i = 0;
            while(1)
            {
                while(str[i] && str[i] == ' ') i++;
                if(!str[i]) return tokens;
                
                int first = i;
                
                while(str[i] && str[i] != ' ') i++;
                int last = i;
                
                tokens.push_back( string(str.begin()+first, str.begin()+last) );
            }
        }
    
        bool wordPattern(string pattern, string str) 
        {
            vector<string> tokens = lex(str);
            
            if(pattern.size() != tokens.size()) return false;
            
            unordered_map<char, string> pattern_map;
            set<string> word_set;
            
            for(int pi=0; pi<pattern.size(); pi++)
            {
                char p = pattern[pi];
                string& w = tokens[pi];
                
                if( !pattern_map.count(p) )
                {
                    if( word_set.find(w) != word_set.end() )
                        return false;
                        
                    pattern_map[p] = w;
                    word_set.insert(w);
                    continue;
                }
                    
                if(pattern_map[p] != w )
                    return false;
            }
            
            return true;
        }
    };

Log in to reply
 

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