[leetcode][python] 290번 - Word Pattern

numango·2024년 10월 16일

leetcode

목록 보기
11/12

문제
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. Specifically:

Each letter in pattern maps to exactly one unique word in s.
Each unique word in s maps to exactly one letter in pattern.
No two letters map to the same word, and no two words map to the same letter.

Example 1:

Input: pattern = "abba", s = "dog cat cat dog"

Output: true

Explanation:

The bijection can be established as:

'a' maps to "dog".
'b' maps to "cat".


두 개의 dict로 번갈아가며 확인하도록 코드를 짰다.

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        s = s.split()

        if len(s) != len(pattern):
            return False
            
        hashmap = {}
        reversemap = {}

        for i in range(len(s)):
            if s[i] in hashmap:
                if hashmap[s[i]] != pattern[i]:
                    return False
            else:
                hashmap[s[i]] = pattern[i]
            if pattern[i] in reversemap:
                if reversemap[pattern[i]] != s[i]:
                    return False
            else:
                reversemap[pattern[i]] = s[i]
        
        return True
     
        

0개의 댓글