C solution using hash37


  • 1
    N
    bool wordPattern(char* pattern, char* str)
    {   
        unsigned int table[26] = {0};
            
        for (; *pattern && *str; pattern++) {
            unsigned int hash = 2139062143;
    
            for(; *str && *str != ' '; str++)
                hash = 37 * hash + *str;
    
            if (*str)
                str++;
                
            if (!table[*pattern - 'a']) {
                for (int i = 0; i < 26; ++i)
                    if (table[i] == hash)
                        return false;
                table[*pattern - 'a'] = hash;
            } else
                if (table[*pattern - 'a'] != hash)
                    return false;
        }
    
        return !*str && !*pattern;
    }
    

  • 0
    L

    Awesome!!!!!!


Log in to reply
 

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