Word Pattern 1

Title: Word Pattern Source: leetcode.com

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

Here follow means a full match, such that 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 dog" should return false.


Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

Java solution

Python solution

Rate this post

One comment on “Word Pattern

  1. Reply Ashu Jain Sep 20,2020 3:34 pm

    #!/usr/bin/env python
    # coding: utf-8

    # # Given a pattern and a string str, find if str follows the same pattern.
    #
    # Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
    #
    # Examples:
    #
    # pattern = “abba”, str = “dog cat cat dog” should return true.
    # pattern = “abba”, str = “dog cat cat fish” should return false.
    # pattern = “aaaa”, str = “dog cat cat dog” should return false.
    # pattern = “abba”, str = “dog dog dog dog” should return false.

    # In[2]:

    #!/usr/bin/env python
    # coding: utf-8

    # function to check pattern and string

    def check_str_pattern(pattern,str):
    global str_list,pattern_list
    str_list=str.split()
    pattern_list=[i for i in pattern]
    map_dict=zip(str_list,pattern_list)
    len_check=check_length_str_pattern(str_list,pattern_list)

    if len_check==True:
    dict={j:i for i,j in map_dict}
    print(dict)
    new_list=[get_key(dict,i) for i in str_list]
    print(“newlist:-“,new_list)
    pt=””.join(new_list)
    print(“Pt:-“,pt)
    print(“Pattern:-“,pattern)
    if pt in pattern:
    print(“Both String and pattern constitue a similar shape”)
    return True
    else:
    print(“But Both String and pattern donot constitue a similar shape”)
    return False
    else:
    return False

    # function to check length of string and pattern

    def check_length_str_pattern(str_list,pattern_list):
    if len(str_list)==len(pattern_list):
    print(“Length for Pattern and string Check:- Passed”)
    return True
    else :
    print(“Length for Pattern and string Check:- Failed”)
    return False

    # function to return key for any value

    def get_key(dict,val):
    for key, value in dict.items():
    if val == value:
    return key

    return “NA”

    # In[4]:Calling Parameters

    pattern=input(“Input pattern to be matched :-“)
    string=input(“Input String”)
    print(“\n”)
    check_str_pattern(pattern,string)

    # In[4]:

    pattern=input(“Input pattern to be matched :-“)
    string=input(“Input String”)
    print(“\n”)
    check_str_pattern(pattern,string)

Leave a Reply