My C++ 0ms solution


  • 0
    A
    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            unordered_map<char, int> tmp1;
            unordered_map<string, int> tmp2;
            
            string str_tmp, key;
            int start = -1;
            int ind_space;
            
            // if both are null
            if(pattern.size()==0 && str.size()==0) return true;
            if(pattern.size()==0 && str.size()!=0) return false;
            if(pattern.size()!=0 && str.size()==0) return false;
            
            str_tmp = str;
            
            for(int i=0; i<pattern.size(); i++){
                
                // cut the string from the start
                str_tmp = str_tmp.substr(start+1);
                
                // find the location of the space
                start = str_tmp.find(' ');
                
                // find the key
                key = str_tmp.substr(0,start);
                
                // if found (one of them)
                if(tmp1.find(pattern[i])!=tmp1.end() && tmp2.find(key)==tmp2.end()) return false;
                if(tmp1.find(pattern[i])==tmp1.end() && tmp2.find(key)!=tmp2.end()) return false;
                
                // if found but they do not match
                if(tmp1.find(pattern[i])!=tmp1.end() && tmp1[pattern[i]] != tmp2[key]) return false;
                
                tmp1[pattern[i]] = i;
                tmp2[key] = i;
                
                // check the number of elements in both strings
                if(i == pattern.size()-1) // at the end character
                {
                    if(start > 0) // there are still more 
                    return false;
                }
            }
            return true;
        }
    };

Log in to reply
 

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