Python solution using 1 dictionary


  • 5
    T
        wordList = str.split()
        n1 = len(pattern)
        n2 = len(wordList)
        if (n1 != n2):
            return False
        else:
            wordList = str.split()
            # wordList = [s.encode('ascii') for s in wordList]
            # pattern = [s.encode('ascii') for s in pattern]
            mydict = {}
            result = True
            for i in range(len(pattern)):
                if (pattern[i] not in mydict):
                    if wordList[i] not in mydict.values():
                        mydict[pattern[i]] = wordList[i]
                    else:
                        result = False
                        break
                else:
                    if (mydict[pattern[i]] != wordList[i]):
                        result = False
                        break
            return result

  • 0
    M

    Nice solution using one dictionary but I feel this will increase the time complexity to O(n^2) because of the line

    wordList[i] not in mydict.values()


  • 0

    @melvin0008 Good point!


Log in to reply
 

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