1190. Reverse Substrings Between Each Pair of Parentheses

You are 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.

Your result should not contain any brackets.se each character in text at most once. Return the maximum number of instances that can be formed.
 

Example 1:

Input: s = “(abcd)”
Output: “dcba”

Example 2:

Input: s = “(u(love)i)”
Output: “iloveu”
Explanation: The substring “love” is reversed first, then the whole string is reversed.

Example 3:

Input: s = “(ed(et(oc))el)”
Output: “leetcode”
Explanation: First, we reverse the substring “oc”, then “etco”, and finally, the whole string.

Constraints:
  • 1 <= s.length <= 2000
  • s only contains lower case English characters and parentheses.
  • It is guaranteed that all parentheses are balanced.

From: LeetCode
Link: 1190. Reverse Substrings Between Each Pair of Parentheses


Solution:

Ideas:

when meeting ), reverse until nearest (, then delete only that (.

Code:
char* reverseParentheses(char* s) {
    int n = strlen(s);
    char* stack = (char*)malloc(n + 1);
    int top = 0;

    for (int i = 0; i < n; i++) {
        if (s[i] == ')') {
            int start = top - 1;

            while (stack[start] != '(') {
                start--;
            }

            int left = start + 1;
            int right = top - 1;

            while (left < right) {
                char temp = stack[left];
                stack[left] = stack[right];
                stack[right] = temp;
                left++;
                right--;
            }

            // remove '(' only
            for (int j = start; j < top - 1; j++) {
                stack[j] = stack[j + 1];
            }
            top--;
        } else {
            stack[top++] = s[i];
        }
    }

    stack[top] = '\0';
    return stack;
}
Logo

智能硬件社区聚焦AI智能硬件技术生态,汇聚嵌入式AI、物联网硬件开发者,打造交流分享平台,同步全国赛事资讯、开展 OPC 核心人才招募,助力技术落地与开发者成长。

更多推荐