prepbook
  • Introduction
  • Some common stuff
    • python __repr__
    • HackerRank input tips
  • Data Structures and Algorithms
    • Breadth first search
    • Depth First Search
    • Dijkstra
    • A* Search Algorithm
    • Binary Search
    • python counter
    • Sorting
      • Merge Sort
      • Quick Sort
    • Priority Queue
  • Multiprocessing vs Threading
  • Common Coding
    • Find loop in lin list
    • Maximum sum subarray
  • Coding
    • Valid palindrome
    • Palindrome number
    • Remove duplicates from sorted array
    • Island perimeter
    • Serialize and Deserialize Binary Tree
    • Valid Soduku
    • Word Pattern
    • Word Pattern II
    • Group Anagrams
    • Implement Trie
    • Deep copy list with random node
    • Palindrome Permutation
    • Combination Sum
    • Clone Graph
    • Generate parenthesis
    • Fibonacci Number
    • LRU Cache
    • Merge two sorted arrays in place
    • Hamming Distance
    • Merge K sorted arrays
    • Kth smalles element in BST
    • Kth largest element in an array
    • Remove duplicates from sorted list
    • Power of 2
    • Nested list weight sum
    • SIngle number in a list
    • Factor combinations
    • Delete node from BST
  • hacker Rank
    • Coding
      • print staircase
      • Drawing book
      • Challenge 0
      • Min-Max sum
  • WorkRelatedCoding
    • Rectangle Overlap
  • Python tips
Powered by GitBook
On this page

Was this helpful?

  1. Coding

Word Pattern

Given apatternand a stringstr, find ifstrfollows the same pattern.

Here follow means a full match, such that there is a bijection between a letter inpatternand a non-empty word instr.

Examples:

  1. pattern ="abba", str ="dog cat cat dog"

    should return true.

  2. pattern ="abba", str ="dog cat cat fish"

    should return false.

  3. pattern ="aaaa", str ="dog cat cat dog"

    should return false.

  4. pattern ="abba", str ="dog dog dog dog"

    should return false.

Notes: You may assumepatterncontains only lowercase letters, andstrcontains lowercase letters separated by a single space.

class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        if not pattern and not str:
            return True

        # since str has words separated by spaces    
        str_arr = str.split()
        if len(str_arr) != len(pattern):
            return False

        dict = {}
        start = 0
        for idx in xrange(len(pattern)):
            ch = pattern[idx]
            substr = ''
            #/////////////////////////////////////////
            # easy to obtain substr when the str has ' ' (space) separating words
            #/////////////////////////////////////////
            for idx2 in xrange(start, len(str)):
                if str[idx2] != ' ':
                    substr += str[idx2]
                else:
                    start = idx2 + 1
                    break;

            #print 'ch: ', ch, ' substr: ', substr, ' start: ', start
            if ch not in dict:
                if substr not in dict.values():
                    #print 'hashing: ', ch, ' -> ', substr
                    dict[ch] = substr
                else:
                    return False

            else:
                if dict[ch] != substr:
                    return False

        return True
PreviousValid SodukuNextWord Pattern II

Last updated 5 years ago

Was this helpful?