একটি এক্সপ্রেশন দেওয়া আছে। সেটিতে ডুপ্লিকেট প্যারেনথেসিস (যেমন ((a+b))) আছে কিনা চেক করুন। স্ট্যাক ব্যবহার করুন: ক্লোজিং ব্র্যাকেট পেলে ওপেনিং ব্র্যাকেট পর্যন্ত পপ করুন, যদি মাঝপথে ১টিও ক্যারেক্টার না থাকে তবে ডুপ্লিকেট।
উদাহরণ
#include <iostream>
#include <stack>
using namespace std;
bool hasDuplicateParentheses(string str) {
stack st;
for (char ch : str) {
if (ch == ')') {
char top = st.top(); st.pop();
int cnt = 0;
while (top != '(') { cnt++; top = st.top(); st.pop(); }
if (cnt < 1) return true;
} else st.push(ch);
}
return false;
}
int main() {
string str = "(5+((7-3)))";
if (hasDuplicateParentheses(str)) cout << "Duplicate parentheses found";
else cout << "No duplicate parentheses";
return 0;
}
আউটপুট
Duplicate parentheses found