[Reverse] LeetCode substring between each pair of brackets

[Problem] Given a string s (containing only lowercase letters and parentheses).

Please order from outside to the brackets, each pair of the matching string inversion layer by layer in parentheses, and returns the final result.

Note that your results should not contain any parentheses.

Example 1 : 
Input: S = " (ABCD) " 
Output: " DCBA "
Example 2 : 
Input: S = " (U (Love) I) " 
Output: " iloveu "
Example 3 : 
Input: S = " (ED (et (OC)) EL) " 
Output: " leetcode "
Example 4 : 
Input: S = " A (bcdefghijkl (MnO) P) Q " 
Output: " apmnolkjihgfedcbq "

prompt:

0 <= s.length <= 2000

s only lowercase letters, and parentheses
we make sure that all the brackets come in pairs.

【answer】

class Solution {
public:
    string reverseParentheses(string s) {
        int len = s.length();
        stack<int> sk;
        for(int i=0;i<len;++i){
            char c = s[i];
            if(c == '(') sk.push(i);
            else if(c == ')'){
                auto it = sk.top();
                sk.pop();
                reverse(s.begin()+it+1,s.begin()+i);
            }
        }
        auto it = s.begin(),e = s.end();
        while(it!=e){
            if(*it=='(' || *it==')') it = s.erase(it);
            else ++it;
        }
        return s;
    }
};

Guess you like

Origin www.cnblogs.com/zhudingtop/p/11668066.html