C++, 0ms solution using unordered_map


  • 1
    C
    class Solution {
    public:
    	bool wordPattern(string pattern, string str) {
    
    		int index = -1;
    		string buff;
    		unordered_map<char, string> hash_cs;
    		unordered_map<string, char> hash_sc;
    		for (int i = 0; i < pattern.size(); i++)
    		{
    			buff.clear();
    			index++;
    			while (index < str.size() && str[index] != ' ')
    				buff.push_back(str[index++]);
    			if (buff.empty())
    				return false;
    			if (hash_cs[pattern[i]] == "" && hash_sc[buff] == 0)
    			{
    				hash_cs[pattern[i]] = buff;
    				hash_sc[buff] = pattern[i];
    			}
    			else
    				if (hash_cs[pattern[i]] != buff || hash_sc[buff] != pattern[i])
    					return false;
    		}
    		if (index<0||index < str.size())
    			return false;
    		return true;
    	}
    };

Log in to reply
 

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