Python solution with no dictionaries usage (commented)


  • 0
    N
    class Solution(object):
        def wordPattern(self, pattern, string):
            string, pattern = string.split(' '), list(pattern)
            if len(pattern) != len(string):
                return False
            chars = [None] * 26
    
            while len(pattern):
    
                # Each char and word is stored only once 
                word, char = string.pop(), pattern.pop()
    
                # >>> ord('a') == 97
                index = ord(char) - 97
    
                # Since the chars array is 26 elements long, the 'word in chars'
                # part is fast and considered a constant time operation if the 
                # input is huge. There's no need to hold the words in a different
                # dictionary
                if chars[index] != word and (word in chars or chars[index]):
                    return False
                elif word not in chars:
                    chars[index] = word
    
            return True
    

Log in to reply
 

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