알고리즘/LeetCode
LeetCode 290. Word Pattern
Timha
2023. 9. 1. 01:39
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.
풀이
두 문자열의 패턴이 동일한지 찾는문제이다.
처음에는 같은 딕셔너리를 사용해서 같이 매칭되게 만들었지만, 테스트케이스에서 패턴의 단어가 중복되는 케이스가 있어서 두개의 딕셔너리를 사용해서 풀었다.
class Solution(object):
def wordPattern(self, pattern, s):
dict1 ={} # pattern 딕셔너리
dict2 ={} # s 딕셔너리
ls= list((s.split(' '))) # s문자열 공백기준으로 나누어서 리스트에 저장
if len(pattern) != len(ls): # pattern의 문자의 개수와 ls의 개수가 다르다면 False
return False
for p,w in zip(pattern,ls): #zip함수로 문자열과 리스트를 순회
if p not in dict1 and w not in dict2: # 각 딕셔너리에 동시에 존재하지 않아야함
dict1[p] = w # dict1과 dict2에 각각 문자를 매핑시켜서 저장
dict2[w] = p
elif p in dict1 and w in dict2: # 둘 다 딕셔너리에 존재한다면 동일한지 체크
if dict1[p] != w or dict2[w] != p:
return False
else: # 어느곳에도 해당안된다면 ex) dict1에는 존재하나
return False # dict2에는 없다면 False 반환
return True
다른사람의 코드
1.
def wordPattern(self, p: str, s: str) -> bool:
words, w_to_p = s.split(' '), dict()
if len(p) != len(words): return False
if len(set(p)) != len(set(words)): return False # for the case w = ['dog', 'cat'] and p = 'aa'
for i in range(len(words)):
if words[i] not in w_to_p:
w_to_p[words[i]] = p[i]
elif w_to_p[words[i]] != p[i]:
return False
return True
2.
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
arr = s.split()
if len(arr) != len(pattern):
return False
for i in range(len(arr)):
if pattern.find(pattern[i]) != arr.index(arr[i]):
return False
return True
1.
문자열을 공백기준으로 나누고 딕셔너리에 저장해서 사용했다.
나는 w = ['dog', 'cat'] and p = 'aa' 의 사례에서 딕셔너리 하나로 사용하다가 생기는 문제 떄문에 딕셔너리를 2개 사용했지만 이 코드에서는 미리 글자수와 단어를 set으로 나누어서 미리 중복되지 않는 set의 원소들의 개수를 확인해서 미리 방지한다. 이런 방법도 있구나.
2.
인덱스를 찾아서 문자열이 동일한지 확인하는 방법이다. 심플하고 간단하다
각 인덱스를 for문으로 돌며 두 단어의 인덱스가 같은 곳을 가르키고 있는지 확인하는 방법이다.
find나 index 둘 중 하나만 사용해도 될 거 같다.