Unordered map implementation


  • 0
    P
        class Solution {
    public:
        bool wordPattern(string pattern, string str);
    
    private:
        unordered_map<char, string> m;
        unordered_map<string, char> c;
    };
    
    bool Solution::wordPattern(string pattern, string str) {
    
        istringstream in(str);
        vector<string> vectorOfStrings;
        string inputString;
    
        int count = pattern.size();
    
        while( in >> inputString)
        {
            vectorOfStrings.push_back(inputString);
        }
    
        if( pattern.size() != vectorOfStrings.size() )
        {
            return false;
        }
    
        for(int i = 0; i < count; ++i)
        {
            m[pattern[i]] =  vectorOfStrings[i];
            c[vectorOfStrings[i]] =  pattern[i];
        }
    
        for(int i = 0; i < count; ++i)
          {
    
    	if(vectorOfStrings[i] != m.at(pattern[i]) )
    	  {
    	    return false;
    	  }
    
    	if(c.at(vectorOfStrings[i]) != pattern[i] )
    	  {
    	    return false;
    	  }
        }
    
        return true;
    }

Log in to reply
 

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