일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- Convert Sorted List to Binary Search Tree
- iterator
- Decorator
- 프로그래머스
- t1
- data science
- 315. Count of Smaller Numbers After Self
- kaggle
- Python Implementation
- Python
- LeetCode
- 715. Range Module
- 컴퓨터의 구조
- Protocol
- 43. Multiply Strings
- Substring with Concatenation of All Words
- concurrency
- 밴픽
- shiba
- 30. Substring with Concatenation of All Words
- 109. Convert Sorted List to Binary Search Tree
- Python Code
- 파이썬
- Class
- DWG
- 운영체제
- 시바견
- Generator
- attribute
- Regular Expression
Archives
- Today
- Total
Scribbling
LeetCode: 97. Interleaving String 본문
DFS version
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
if len(s1) + len(s2) != len(s3):
return False
self.s1 = s1
self.s2 = s2
self.s3 = s3
self.dp = set()
return self.dfs(0, 0, 0)
def dfs(self, i, j, k):
if (i, j, k) in self.dp:
return False
if k == len(self.s3):
return True
if i < len(self.s1) and self.s1[i] == self.s3[k]:
if self.dfs(i+1, j, k+1):
return True
if j < len(self.s2) and self.s2[j] == self.s3[k]:
if self.dfs(i, j+1, k+1):
return True
self.dp.add((i, j, k))
return False
Stack version
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
l, r, z = len(s1), len(s2), len(s3)
if l + r != z:
return False
stack, visited = [(0, 0)], set()
while stack:
x, y = stack.pop()
if x + y == z:
return True
if x + 1 <= l and s1[x] == s3[x+y] and (x+1, y) not in visited:
stack.append((x+1, y))
visited.add((x+1, y))
if y + 1 <= r and s2[y] == s3[x+y] and (x, y+1) not in visited:
stack.append((x, y+1))
visited.add((x, y+1))
return False
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 95. Unique Binary Search Trees II (0) | 2021.10.13 |
---|---|
LeetCode: 92. Reverse Linked List II (0) | 2021.10.12 |
LeetCode: 93. Restore IP Addresses (0) | 2021.10.11 |
LeetCode: 91. Decode Ways (0) | 2021.10.11 |
LeetCode: 100. Same Tree (0) | 2021.10.11 |