Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tìm chỉ số ngoặc đóng tương ứng cho ngoặc mở cho trước trong biểu thức trong C++


Cho biểu thức có ngoặc, cho chỉ số ngoặc mở, tìm chỉ số ngoặc đóng tương ứng. Ví dụ "(25*6+(88-32+(50/10)+20))", chỉ số 6 → 23.

Dùng stack: từ chỉ số cho trước, gặp '(' push, gặp ')' pop, khi stack rỗng trả về chỉ số hiện tại.

Ví dụ

#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); }

Kết quả

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