LeetCode

[LeetCode] Easy - 290 Word Pattern

NIMHO 2023. 1. 2. 16:21
728x90

▶290 - Word Pattern

문제

Given a pattern and a string s, find if s 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 s.

 

예제

Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false

 

풀이

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        arr = s.split(' ')
        if len(pattern) != len(arr):
            return False
        pdic = {}
        sdic = {}
        for i in range(len(pattern)):
            p = pattern[i]
            a = arr[i]
            if (p in pdic and pdic[p] != a) or (a in sdic and sdic[a] != p):
                return False
            pdic[p] = a
            sdic[a] = p

        return True
728x90