ปัญหา
ให้สตริงที่มีวงเล็บเปิด '(' และวงเล็บปิด ')' ปนอยู่ในตัวอักษร ต้องการลบวงเล็บที่เกินออก เพื่อให้สตริงสมดุล (balanced parentheses)
ตัวอย่าง: ")Tutor)ials(p(oin)t(...)" → "Tutorials(p(oin)t(...))"
อัลกอริทึม
- สร้างตัวแปร count = 0 นับวงเล็บเปิดที่ยังไม่ถูกปิด
- วนอ่านตัวอักษรทีละตัวจากซ้ายไปขวา:
- ถ้าเป็น '(' → พิมพ์ออกมา และ count++
- ถ้าเป็น ')' และ count > 0 → พิมพ์ออกมา และ count--
- ถ้าเป็น ')' และ count == 0 → ข้าม (ลบออก)
- ถ้าเป็นตัวอักษรอื่น → พิมพ์ออกมา
- หลังจบลูป ถ้า count > 0 → เพิ่ม ')' ท้ายสตริง count ครั้ง
ตัวอย่างโค้ด C++
#include <iostream>
#include <string>
using namespace std;
void balanceBrackets(string str) {
int count = 0;
int n = str.length();
for (int i = 0; i < n; i++) {
if (str[i] == '(') {
cout << str[i];
count++;
}
else if (str[i] == ')' && count != 0) {
cout << str[i];
count--;
}
else if (str[i] != ')') {
cout << str[i];
}
}
// เพิ่มวงเล็บปิดที่ขาดไป
while (count-- > 0)
cout << ')';
}
int main() {
string str = ")Tutor)ials(p(oin)t(...)";
cout << "Original string: " << str << endl;
cout << "Balanced string: ";
balanceBrackets(str);
cout << endl;
return 0;
}
ผลลัพธ์
Original string: )Tutor)ials(p(oin)t(...) Balanced string: Tutorials(p(oin)t(...))