在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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便