Leetcode Top 100
10. Regular Expression Matching (해결 x 솔루션 o)
오리_꿀꿀
2021. 1. 7. 18:09
p배열로 s를 만들 수 있는지 판단하는 문제이다.
- '.' 은 모든 문자 대체 가능
- '*'은 앞에 오는 알파벳 여러개 사용 또는 비사용 가능
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if not p:
return not s
#p배열과 s배열이 다 빈 경우 -> 문자열 완성이므로 -> True
first_match = bool(s) and p[0] in {s[0], '.'}
#s가 비어있지 않고 p[0]이 s[0]또는 '.'일 경우 True
if len(p) >= 2 and p[1]=='*':
return (self.isMatch(s,p[2:]) or (first_match and self.isMatch(s[1:],p)))
#p의 길이가 2이상이고 p[1]이'*' 일 경우
# 1. isMatch(s,p[2:])을 통해 '알파벳*' 사용안하고 스킵
# 2. 첫문자가 같을 경우(first_match = True) 알파벳 사용 후 한칸 뒤로 옮김
else:
return first_match and self.isMatch(s[1:],p[1:])
# 첫문자가 같을 경우 둘 다 한칸씩 옮김
# 슬라이싱 p[2:] 을 통해서 계속 문자열을 줄여나가며 재귀함수를 사용하는 것이 핵심 포인트이다.