พิจารณาว่าเรามีนิพจน์ที่มีวงเล็บเหลี่ยม หากได้รับดัชนีของวงเล็บเริ่มต้น เราต้องหาวงเล็บปิดท้ายของวงเล็บนั้น ดังนั้น หากนิพจน์เป็นแบบ:(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