C++中括號間字串的反轉


假設我們有一個字串 s,它包含小寫字母和括號。我們必須反轉每一對匹配括號內的字串,從最裡面的開始。並且結果不應包含任何括號。所以如果輸入類似於“(hel(lowo)rld)” ,那麼輸出將是“dlrlowoleh”,所以從一開始,它像這樣改變: “(hel(lowo)rld)” → “(helowolrld)” → “dlrowoleh”。

為了解決這個問題,我們將遵循以下步驟:

  • n := 字串的大小,建立一個名為 par 的陣列,其長度為 n,定義一個棧 st

  • 對於 i 的範圍從 0 到 n – 1

    • 如果 s[i] 是左括號,則將 i 插入 st

    • 否則,當 s[i] 是右括號時,則 j := st.pop(),par[i] := j 且 par[j] := i

  • 定義一個空字串 ret

  • 對於 i := 0,d := 1,i < n,i 增加 d

    • 如果 s[i] 是左括號或 s[i] 是右括號,則 i := par[i],d := -d 否則 ret 增加 s[i]

  • 返回 ret

示例(C++)

讓我們看看下面的實現以獲得更好的理解:

 線上演示

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   void out(vector <int>& v){
      for(int i = 0; i < v.size(); i++){
         cout << v[i] << " " ;
      }
      cout << endl;
   }
   string reverseParentheses(string s) {
      int n = s.size();
      vector <int> par(n);
      stack <int> st;
      for(int i = 0; i < n; i++){
         if(s[i] == '('){
            st.push(i);
         }
         else if(s[i] == ')'){
            int j = st.top();
            st.pop();
            par[i] = j;
            par[j] = i;
         }
      }
      string ret = "";
      for(int i = 0, d = 1; i < n; i += d){
         if(s[i] == '(' || s[i] == ')'){
            i = par[i];
            d = -d;
         }
         else{
            ret += s[i];
         }
      }
      out(par);
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.reverseParentheses("(hel(lowo)rld)"));
}

輸入

"(hel(lowo)rld)"

輸出

13 0 0 0 9 0 0 0 0 4 0 0 0 0
dlrlowoleh

更新於: 2020-04-29

303 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.