C++ solution without using map


  • 0
    R
    bool wordPattern(string pattern, string str) {
        string charMap[26];
        
        for (int i = 0; i < 26; i++)
        {
            charMap[0] = "";
        }
        
        int sz1 = pattern.length();
        int sz2 = str.length();
        
        if (sz1 == 0 && sz2 == 0)
            return true;
        
        if (sz1 == 0 || sz2 == 0)
            return false;
        
        int j = 0;
        int i = 0;
        for (i = 0; i < sz1 && j < sz2; i++)  
        {
            char ch = pattern.at(i);
            string toSearch = charMap[ch - 'a'];
            string toFind = "";
            while (j < sz2 && str.at(j) != ' ')
            {
                toFind += str.at(j);
                j++;
            }
            if (j < sz2 && str.at(j) == ' ')
                j++;
            
            if (toFind.empty())
                return false;
            
            if (toSearch.empty())
            {
                for (int k = 0; k < 26; k++)
                {
                    if (charMap[k] == toFind)
                        return false;
                }
    
                charMap[ch - 'a'] = toFind;
            }
            else if (toSearch != toFind)
                return false;
        }
        if (j != sz2 || i != sz1)
            return false;
        
        return true;
    }

Log in to reply
 

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