My C++ 0ms solution, using two maps


  • 0
    L
    bool wordPattern(string pattern, string str){
    	unordered_map<char, string> MAP1;
    	unordered_map<string, char> MAP2;
    	
    	int pos=0, i=0;
    	size_t found;
    	while(1){
    		char c = pattern[i++];
    		found = str.find(' ', pos);
    		string s = str.substr(pos,found-pos);
    
    		if (MAP1.find(c) == MAP1.end()){
    			MAP1[c] = s;
    		}
    		else if (MAP1[c] != s)	return false;
    		if (MAP2.find(s) == MAP2.end()){
    			MAP2[s] = c;
    		}
    		else if (MAP2[s] != c)	return false;
    
    		if (found == string::npos || i==pattern.size())	break;
    		pos = found+1;
    	}
    	if (i==pattern.size() && found==string::npos)	return true;
    	else	return false;
    }

Log in to reply
 

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