forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check-if-there-is-a-valid-parentheses-string-path.py
43 lines (40 loc) · 1.5 KB
/
check-if-there-is-a-valid-parentheses-string-path.py
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
31
32
33
34
35
36
37
38
39
40
41
42
43
# Time: O((m * n) * (m + n) / 32)
# Space: O(n * (m + n) / 32)
# dp with bitsets
class Solution(object):
def hasValidPath(self, grid):
"""
:type grid: List[List[str]]
:rtype: bool
"""
if (len(grid)+len(grid[0])-1)%2:
return False
dp = [0]*(len(grid[0])+1)
for i in xrange(len(grid)):
dp[0] = int(not i)
for j in xrange(len(grid[0])):
dp[j+1] = (dp[j]|dp[j+1])<<1 if grid[i][j] == '(' else (dp[j]|dp[j+1])>>1
return dp[-1]&1
# Time: O(m * n)
# Space: O(n)
# dp, optimized from solution1 (wrong answer)
class Solution_WA(object):
def hasValidPath(self, grid):
"""
:type grid: List[List[str]]
:rtype: bool
"""
if (len(grid)+len(grid[0])-1)%2:
return False
dp = [[float("inf"), float("-inf")] for _ in xrange(len(grid[0])+1)]
for i in xrange(len(grid)):
dp[0] = [0, 0] if not i else [float("inf"), float("-inf")]
for j in xrange(len(grid[0])):
d = 1 if grid[i][j] == '(' else -1
dp[j+1] = [min(dp[j+1][0], dp[j][0])+d, max(dp[j+1][1], dp[j][1])+d]
# bitset pattern is like xxx1010101xxxx (in fact, it is not always true in this problem where some paths are invalid)
if dp[j+1][1] < 0:
dp[j+1] = [float("inf"), float("-inf")]
else:
dp[j+1][0] = max(dp[j+1][0], dp[j+1][1]%2)
return dp[-1][0] == 0