Reverse Substrings Between Each Pair of Parentheses(C++反转每对括号间的子串)

解题思路:

(1)使用栈保存前缀字符串,遇到右括号翻转字符串,同时加上最近的前缀字符串

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;
    }
};

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/114655594