본문 바로가기

Algorithm/Leetcode

[Top Interview 150 - Hashmap] 290. Word Pattern

[Q] [Easy]

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.

 

  • 길이 다르면 애초에 아니니까 따로 빼줬다.
  • dict 하나 만들어놓고 pattern 에 해당하는 string 을 넣어줬다.
  • 한 쪽에 없는데 다른데 있으면 False, 만약에 dict[pattern] != string 이어도 False
# Answer

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

        s = s.split(' ')

        if len(pattern) != len(s):
            return False

        tmp = dict()

        for pat, st in zip(pattern, s):
            if not pat in tmp:
                if not st in tmp.values():
                    tmp[pat] = st
                else:
                    return False
            else:
                if tmp[pat] != st:
                    return False
            
        return True