Leetcode 1298 Solution

This article provides solution to leetcode question 1298 (reverse-substrings-between-each-pair-of-parentheses)

https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses

Solution

class Solution:
    def reverseParentheses(self, s: str) -> str:
        stack = []
        pair = [None] * len(s)
        cnt = 0

        for i, ch in enumerate(s):
            if ch == '(':
                stack.append(i)
                cnt += 1
            elif ch == ')':
                j = stack.pop()

                pair[i] = j
                pair[j] = i
                cnt += 1

        i = 0
        d = 1
        ans = ""

        while len(ans) + cnt < len(s):
            if s[i] == '(' or s[i] == ')':
                i = pair[i]
                d = -d
            else:
                ans += s[i]

            i += d

        return ans