找到 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.