สตริงคืออาร์เรย์ของอักขระ ในปัญหานี้ เราได้รับสตริงที่มีวงเล็บเปิดและปิด และเราจะสร้างสมดุลให้กับสตริงนี้โดยลบวงเล็บเพิ่มเติมออกจากสตริง
มาดูตัวอย่างกัน
Input : “)Tutor)ials(p(oin)t(...)” Output : “Tutorials(p(oin)t(...))”
เพื่อแก้ปัญหานี้ เราจะสำรวจผ่านสตริงและตรวจสอบวงเล็บที่ตรงกัน สำหรับวงเล็บที่ไม่ตรงกัน ให้ลบวงเล็บปิด
อัลกอริทึม
Step 1 : Traverse the string from left to right. Step 2 : For opening bracket ‘(’ , print it and increase the count. Step 3 : For occurence of closing bracket ‘)’ , print it only if count is greater than 0 and decrease the count. Step 4 : Print all characters other than brackets are to be printed in the array. Step 5 : In the last add closing brackets ‘)’ , to make the count 0 by decrementing count with every bracket.
ตัวอย่าง
#include<iostream>
#include<string.h>
using namespace std;
void balancedbrackets(string str){
int count = 0, i;
int n = str.length();
for (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];
}
if (count != 0)
for (i = 0; i < count; i++)
cout << ")";
}
int main() {
string str = ")Tutor)ials(p(oin)t(...)";
cout<<"Original string : "<<str;
cout<<"\nBalanced string : ";
balancedbrackets(str);
return 0;
} ผลลัพธ์
Original string : )Tutor)ials(p(oin)t(...) Balanced string : Tutorials(p(oin)t(...))