考虑我们有一个带有方括号的表达式。如果给定了一个起始括号的索引,我们必须找到该起始括号的结尾。因此,如果表达式类似于:(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