LeetCode ---- Word Pattern

Source: Internet
Author: User

LeetCode ---- Word Pattern

Word Pattern

 

GivenpatternAnd 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 dogShocould return true.
  2. Pattern =abba, Str =dog cat cat fishShocould return false.
  3. Pattern =aaaa, Str =dog cat cat dogShocould return false.
  4. Pattern =abba, Str =dog dog dog dogShocould return false.

     

    Notes:
    You may assumepatternContains only lowercase letters, andstrContains lowercase letters separated by a single space.


    Analysis:

    Matches the specified string by mode.

    My approach is to build a Pattern Dictionary pd = {'A': None, 'B': None} based on a pattern such as "aabb }. Split the given string, such as "dog cat", by space. Then, the corresponding string and the dictionary key are sorted in order. If they do not match, the mode is not met. Finally, determine whether the strings corresponding to different key values in the dictionary are the same. If the strings are the same, they do not match the pattern.

     

    Code:

     

    class Solution(object):    def wordPattern(self, pattern, str):                :type pattern: str        :type str: str        :rtype: bool                pd = dict(map(lambda a: (a, None), list(pattern)))        slst = str.split()        if len(pattern) != len(slst):            return False        for i in range(len(slst)):            if pd[pattern[i]] is None:                pd[pattern[i]] = slst[i]            else:                if pd[pattern[i]] != slst[i]:                    return False        s = set()        for i in pd:            s.add(pd[i])        if len(s) != len(pd):            return False        return True

     

     

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.