brackets 匹配问题

#include <iostream>
#include <stack>
#include <string>
using namespace std;
int checkNotRight(string);
int process(string, int&, int&);

int main(void){
	string s;
	int first_end=0,num_swap=0;
	cin>>s;
	if(process(s,first_end,num_swap) == -1)
		cout<<"brackets are not coupled"<<endl;
	else
		cout<<"first_end="<<first_end<<"  "<<"num_swap="<<num_swap<<endl;
}
int process(string s, int& first_end, int& num_swap){
	if(checkNotRight(s) == false)
		return -1;
	stack<char> stackMain;
	stack<char> stackSub;
	int firstEnd=0,numSwap=0;//first_end,num_swap are for output
	int firstEndFlag=false;
	for(int i=0;i<s.length();i++){
		if(s[i] == '(' && stackSub.empty() ) 
			stackMain.push(s[i]);
		else if(s[i]=='(' && !stackSub.empty()) {
			//has ')" in stackSub,
			if(!firstEndFlag) firstEnd +=2;
			numSwap += stackSub.size();
			stackSub.pop();
		}
		else if(s[i] == ')' && !stackMain.empty() ){
			//case 1, stackMain has '(', so stackMain pop
			stackMain.pop(); 
			if(!firstEndFlag) firstEnd += 2;
		}
		else if(s[i]==')' && stackMain.empty()){
			stackSub.push(s[i]);
		}
		if(stackMain.empty() && stackSub.empty()){ 
			//such as () or (())
			firstEndFlag = true;
			firstEnd -= 1;
		}
	}
	if(s[0] == ')') {
		firstEnd=1;
		//firstEndFlag=true;
	}
	first_end = firstEnd;
	num_swap  = numSwap;
	return 0;
}
int checkNotRight(string s){
	int length = s.length();
	if(length % 2==1)
		return false;//error
	int num_left=0, num_right=0;
	int index=0;
	while(length--){
		if(s[index] == '(') num_left++;
		else if(s[index] == ')') num_right++;
		else cout<<"error"<<endl;
		index++;
	}
	if(num_left != num_right) return false;
	else return true;
}





### Python 中括号匹配算法的实现 为了确保字符串中的括号能够正确匹配,可以采用栈的数据结构来辅助验证。每当遇到左括号时将其压入栈中;而当遇到右括号时,则尝试弹出栈顶元素并检查两者是否为一对匹配的括号。 下面展示了一个完整的解决方案: ```python def is_valid_parentheses(s: str) -> bool: stack = [] brackets = {')': '(', ']': '[', '}': '{'} # 使用字典存储括号的对应关系, 使用反括号作key方便查询对应的括号[^1] for char in s: if char in brackets.values(): stack.append(char) elif char in brackets.keys(): if not stack or stack.pop() != brackets[char]: return False else: continue return len(stack) == 0 ``` 此函数接收一个由字符组成的字符串作为输入参数 `s` ,并通过遍历该字符串内的每一个字符来进行操作。如果当前字符属于开括号集合(即 `{ '(' , '[' , '{' }`),则直接加入到栈内保存起来等待后续闭合;如果是闭括号的话就需要进一步判断此时栈是否为空以及最近一次存入的是不是与之相配对的那个开括号——只有在这两种情况都满足的前提下才能继续往下执行程序逻辑,否则就说明出现了不合法的情形应当立即返回错误标志位 `False` 。最后,在完成整个循环之后还需要额外确认一遍栈里有没有残留下来的未被关闭过的开括号存在,以此决定最终的结果应该是真还是假。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值