작심삼일

[LeetCode] 290 | Word Pattern | Python 본문

스터디/코테

[LeetCode] 290 | Word Pattern | Python

yun_s 2022. 1. 17. 10:20
728x90
반응형

문제 링크: https://leetcode.com/problems/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.


조건

  • 1 <= pattern.length <= 300
  • pattern contains only lower-case English letters.
  • 1 <= s.length <= 3000
  • s contains only lowercase English letters and spaces ' '.
  • s does not contain any leading or trailing spaces.
  • All the words in s are separated by a single space.

내 풀이

 

먼저, s를 s.split(' ')을 이용해 나눈 후, pattern과 s의 길이가 다르면 False를 리턴한다.

그 뒤, 순서대로 pattern[n]과 s[n]을 dictionary에 저장하는데, 각각 일대일 대응만 되어야 한다.

(ex. a $\rightarrow$ dog, b $\rightarrow$ cat: O)

(ex. a $\rightarrow$ dog, b $\rightarrow$ dog: X)

(ex. a $\rightarrow$ dog, a $\rightarrow$ cat: X)

그렇기때문에 첫번째 코드에서는 dictionary를 두 개 이용했고, 두번째 코드는 dictionary를 하나만 사용해서 해결했다.


코드

# dictionary 한 개
class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        check, rcheck = {}, {}
        s = s.split(' ')
        if len(s) != len(pattern):
            return False
        
        for n in range(len(pattern)):
            if pattern[n] not in list(check.keys()):
                check[pattern[n]] = s[n]
            else:
                if check[pattern[n]] != s[n]:
                    return False
            
            if s[n] not in list(rcheck.keys()):
                rcheck[s[n]] = pattern[n]
            else:
                if rcheck[s[n]] != pattern[n]:
                    return False
                
        return True
# dictionary 두 개
class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        s = s.split(" ")
        
        if len(pattern) != len(s):
            return False
        
        his = dict()
        for pat, strs in zip(pattern, s):
            if not pat in his:
                if not strs in his.values():
                    his[pat] = strs
                else:
                    return False
            else:
                if his[pat] != strs:
                    return False
                
        return True
728x90
반응형
Comments