Straightforward C++ solution, 2 loops


  • 0
    Y
    bool wordPattern(string pattern, string str) {
        if (pattern.length() == 0)
            return false;
        string item;
        stringstream ss(str);
    	vector<string> splited;
    	while (getline(ss, item, ' '))
    	{
    		if (item.length() > 0)
    			splited.push_back(item);
    	}
    	if (pattern.length() != splited.size())
    	    return false;
        
    	for (int idx = 0; idx < pattern.length() - 1; idx++)
    	{
    	    for (int tidx = idx + 1; tidx < pattern.length(); tidx++)
    	    {
    	        if ((pattern[idx] == pattern[tidx]) != (splited[idx] == splited[tidx]))
    	            return false;
    	    }
    	}
    	return true;
    }

Log in to reply
 

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