반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 290 | Word Pattern | Python 본문
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
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 142 | Linked List Cycle II | Python (0) | 2022.01.19 |
---|---|
[백준] 2839번 | 설탕 배달 | C (0) | 2022.01.17 |
[LeetCode] 452 | Minimum Number of Arrows to Burst Balloons | Python (0) | 2022.01.13 |
[LeetCode] 701 | Insert into a Binary Search Tree | Python (0) | 2022.01.12 |
[LeetCode] 67 | Add Binary | Python (0) | 2022.01.10 |
Comments