Reverse Substrings Between Each Pair of Parentheses (C++ reverses the substrings between each pair of parentheses)

Problem-solving ideas:

(1) Use the stack to save the prefix string, turn the string when the right parenthesis is encountered, and add the nearest prefix string at the same time

class Solution {
public:
    string reverseParentheses(string s) {
        stack<string> st;
        int i=0;
        string str="";
        while(i<s.length()) {
            if(s[i]=='(') {
                st.push(str);
                str="";
            } else if(s[i]==')') {
                reverse(str.begin(),str.end());
                str=st.top()+str;
                st.pop();
            } else str+=s[i];
            i++;
        }
        return str;
    }
};

 

Guess you like

Origin blog.csdn.net/coolsunxu/article/details/114655594