查找表达式是否在C ++中具有重复的括号
考虑我们有一个表达式exp,我们必须检查exp周围是否有重复的括号。如果一个子表达式被一组以上的括号包围,则该表达式将具有重复的括号。例如,如果表达式类似于-
(5+((7−3)))
这里的子表达式(7–3)被两个括号对包围,因此它们是重复的括号。
为了解决这个问题,我们将使用堆栈。我们将遍历exp中的每个字符,如果该字符是开括号'('或任何运算符或操作数,则将其推入堆栈。当该字符是闭合括号时,则反复从堆栈中弹出字符直到找到匹配的开括号,然后使用一个计数器,该值将在开括号和闭括号对之间遇到的每个字符递增,该值等于计数器的值小于1,然后是一对重复的括号找到,否则找不到。
示例
#include<iostream>
#include<stack>
using namespace std;
bool hasDuplicateParentheses(string str) {
stack<char> stk;
for (int i = 0; i<str.length(); i++) {
char ch = str[i];
if (ch == ')') {
char top = stk.top();
stk.pop();
int count = 0;
while (top != '(') {
count++;
top = stk.top();
stk.pop();
}
if(count < 1) {
return true;
}
}
else
stk.push(ch);
}
return false;
}
int main() {
string str = "(5+((7-3)))";
if (hasDuplicateParentheses(str))
cout << "Duplicate parentheses has Found";
else
cout << "No Duplicates parentheses has Found ";
}输出结果
Duplicate parentheses has Found