관리 메뉴

솜씨좋은장씨

[leetCode] 290. Word Pattern (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 290. Word Pattern (Python)

솜씨좋은장씨 2020. 8. 4. 00:34
728x90
반응형

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.

 

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true

Example 2:

Input:pattern = "abba", str = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false

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

 

Solution

class Solution:
    def wordPattern(self, pattern: str, string: str) -> bool:
        string_s = string.split(' ')
        
        answer = True
        
        check_dict = {}
        
        for p, s in zip(pattern, string_s):
            if p not in check_dict.keys():
                check_dict[p] = s
            else:
                if check_dict[p] != s:
                    answer = False
                    break
        if (len(set(check_dict.keys())) != len(set(check_dict.values()))) or (len(pattern) != len(string_s)):
            answer = False
        return answer

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

 

Comments