Scribbling

32. Longest Valid Parentheses 본문

Computer Science/Coding Test

32. Longest Valid Parentheses

focalpoint 2021. 9. 4. 00:13

무지성 포칼포인트의 답...

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        if not s:
            return 0
        
        mem = [0] * len(s)
        stack = []
        length = 0
        for i in range(len(s)):
            char = s[i]
            if char == '(':
                stack.append(char)
                length = 0
            else:
                if not stack:
                    length = 0
                else:
                    top = stack.pop()
                    if top == '(':
                        length += 2
                        if i - length >= 0 and s[i-length] == ')':
                            length += mem[i-length]
                    else:
                        length = 0
            mem[i] = length
        return max(mem)

 

괴수의 답...

class Solution:
    def longestValidParentheses(self, s: str) -> int:
        stack = []
        dp = [0] * (len(s) + 1)     
        for i, c in enumerate(s):
            if c == '(':
                stack.append(i)
            else:
                if stack:
                    corresponding_idx = stack.pop()
                    dp[i+1] = dp[corresponding_idx] + i - corresponding_idx + 1
        return max(dp)

 

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 48. Rotate Image  (0) 2021.09.05
39. Combination Sum  (0) 2021.09.04
LeetCode: 29. Divide Two Integers  (0) 2021.09.02
LeetCode: 50. Pow(x, n)  (0) 2021.09.02
LeetCode: 30. Substring with Concatenation of All Words  (0) 2021.08.29