koenjazh-CNfresde
짬뽕얼큰하게의 맨땅에 헤딩 :: Reverse Substrings Between Each Pair of Parentheses

summary

  • Given a string s that consists of lower case English letters and brackets, reverse the strings in each pair of matching parentheses, starting from the innermost one.

approach

  • This solution uses a stack to keep track of the indices of the characters that need to be reversed
  • When a closing parenthesis is encountered, the solution pops the corresponding opening parenthesis index from the stack, reverses the substring between these two indices, and then removes the opening parenthesis from the stack.

complexity

  • O(N)

explain

  • The solution iterates over the string s
  • When it encounters an opening parenthesis, it pushes the current length of the string onto the stack
  • When it encounters a closing parenthesis, it pops the corresponding opening parenthesis index from the stack, reverses the substring between these two indices, and then removes the opening parenthesis from the stack
  • The solution continues this process until it has processed the entire string.

Solution Code:


class Solution {
public:
    
    string reverseParentheses(string s) {
        string res = "";
        int mystack[2001];
        int stackIdx = 0;
        int N = s.length();
        int idx = 0;
        for(int i = 0 ; i < N; i++){
            if (s[i] == '('){
                mystack[stackIdx++] = res.length();
            } else if (s[i] == ')'){
                int popIdx = mystack[--stackIdx];
                reverse(res.begin()+popIdx, res.end());
            } else {
                res += s[i];
            }
        }
        return res;
    }
};

'알고리즘' 카테고리의 다른 글

Create Binary Tree From Descriptions  (0) 2025.02.03
Maximum Score From Removing Substrings  (0) 2025.02.02
Crawler Log Folder  (0) 2025.02.02
Average Waiting Time  (0) 2025.02.02
Find the Winner of the Circular Game  (0) 2025.02.02
블로그 이미지

짬뽕얼큰하게

,