找到 C++ 表示式中給定起始括號的結束括號的索引


考慮我們有一個帶括號的表示式。如果指定了一個起始括號的索引,我們需要找到其結束的結束括號。因此,如果表示式類似於:(25*6+(88-32+(50/10)+20)),並且起始括號的索引為 6,則結束括號將位於位置 23。

在此,我們將使用堆疊資料結構解決此問題。我們將從給定索引開始遍歷表示式,並開始壓入起始括號,當找到結束括號時,彈出堆疊中的元素,當堆疊為空時,返回索引。

示例

 即時演示

#include<iostream>
#include<stack>
using namespace std;
void getEndingBracketIndex(string exp, int index){
   int i;
   if(exp[index]!='('){
      cout << exp << "Closing bracket of parentheses started at " << index << " present at index -1\n";
      return;
   }
   stack <int> stk;
   for(i = index; i < exp.length(); i++){
      if(exp[i] == '(')
         stk.push(exp[i]);
      else if(exp[i] == ')'){
         stk.pop();
         if(stk.empty()){
            cout << exp << ", Closing bracket of parentheses started at " << index << " present at index " << i << "";
            return;
         }
      }
   }
   cout << exp << ", Closing bracket of parentheses started at " << index << " present at index -1";
}
int main() {
   getEndingBracketIndex("(25*6+(88-32+(50/10)+20))", 6);
}

輸出

(25*6+(88-32+(50/10)+20)), Closing bracket of parentheses started at 6 present at index 23

更新時間:18-Dec-2019

339 次瀏覽

Kickstart 您的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.