LeetCode - 1190. Reverse Substrings Between Each Pair of Parentheses

LeetCode - 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.

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

Input: s = “(u(love)i)”
Output: “iloveu”

Input: s = “(ed(et(oc))el)”
Output: “leetcode”

Input: s = “a(bcdefghijkl(mno)p)q”
Output: “apmnolkjihgfedcbq”

  就是從最裏邊的括號開始,一對兒括號中的字符串翻轉一次。有左右括號的題,一般都用 stack,這道題也可以用。每次讀到一個左括號,記錄目前的字符串的長度,也就是左括號在整個字符串中的位置,下一次讀到右括號,直接翻轉這區間內的字符串即可。

string reverseParentheses(string s) {
    stack<int> st;
    string res;
    for(const char& c : s){
        if(c == '(')
            st.push(res.length());
        else if(c == ')'){
            const int t = st.top();
            st.pop();
            reverse(res.begin() + t, res.end());
        }
        else
            res += c;
    }
    return res;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章