290. Word Pattern [Easy] (Python)

Source: Internet
Author: User

Topic links

https://leetcode.com/problems/word-pattern/

Original title

Given a pattern and a string str, find if STR follows the same pattern.

Here follow means a full match, such this there is a bijection between a letter in pattern and a non-empty word in Str.

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" should return false.

Notes:
Assume pattern contains only lowercase letters and STR contains lowercase letters separated by a single space.

Topic translation

Given a pattern (pattern) and a string (str), determine whether the string matches the pattern. The match here refers to the exact match, which is the double shot between the characters in the pattern and the non-empty words in Str.
This problem is very similar to the other one, the solution is basically the same, see:
205. Isomorphic Strings

Method of Thinking Idea one

Each character of the pattern is traversed at the same time, and each word in STR establishes their mapping, which returns False when there is a violation of the mapping relationship. In addition, because it is a double shot, the different characters in the pattern can not be mapped to the same word, so do this check.

Code

 class solution(object):     def wordpattern(self, pattern, str):        "" : Type Pattern:str:type str:str:rtype:bool "" "Words = Str.split ("')ifLen (words)! = Len (pattern):return FalseHashMap = {} Mapval = {} forIinchXrange (len (pattern)):ifPattern[i]inchHashMapifHashmap[pattern[i]]! = Words[i]:return False            Else:ifWords[i]inchMapval:return FalseHashmap[pattern[i]] = Words[i] mapval[words[i]] =True        return True
Idea two

For pattern and STR, each character is recorded in an array, or where word first appears. When both pattern and Str are traversed, false is returned if they are found to be different in character at one location or where word first appears.

Code

class Solution(object):    def wordPattern(self, pattern, str):        """        :type pattern: str        :type str: str        :rtype: bool        """        words = str.split(‘ ‘)        if len(words) != len(pattern):            returnFalse        return map(pattern.find, pattern) == map(words.index, words)
Three Ideas

According to the description of the topic, how many different types of characters are there in pattern, and how many different types of Word are str? If we write the mapping in the form of a pair of characters, such as (' A ', ' dog ') that indicates that the character ' a ' in pattern is mapped to ' dog ' in str, then the number of mappings is the same as that of the characters in pattern.
So the method is essentially a judgment mapping is not a double shot.

Code

class  solution   (object) :  def  wordpattern  :   words = Str.split (" ) if  len (words)! = Len (pattern): return  false  return  len (set (pattern)) = = Len (set (words)) = = L En (Set (pattern, words))  

PS: Novice Brush Leetcode, new handwritten blog, write wrong or write not clear also please help point out, thank you!
Reprint Please specify: http://blog.csdn.net/coder_orz/article/details/51693647

290. Word Pattern [Easy] (Python)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.