Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาดัชนีของวงเล็บปิดสำหรับวงเล็บเปิดที่กำหนดในนิพจน์ใน C++

พิจารณาว่ามีนิพจน์ที่มีวงเล็บ หากดัชนีของวงเล็บเปิดหนึ่งตัวถูกกำหนด เราต้องหาวงเล็บปิดของมัน ดังนั้นถ้านิพจน์เป็นแบบ: (25*6+(88-32+(50/10)+20)) และดัชนีของวงเล็บเปิดคือ 6 วงเล็บปิดจะอยู่ที่ตำแหน่ง 23

ที่นี่เราจะใช้โครงสร้างข้อมูล Stack (กอง) เพื่อแก้ปัญหานี้ เราจะเดินทางผ่านนิพจน์จากดัชนีที่กำหนด และเริ่ม push วงเล็บเปิด เมื่อพบวงเล็บปิด ให้ pop องค์ประกอบจาก stack เมื่อ stack ว่าง ให้คืนค่าดัชนี

ตัวอย่าง

#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