查找C++表达式中是否存在重复括号
假设我们有一个表达式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
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP