leetcode刷题(七)

本文深入探讨了括号匹配的有效性判断算法,包括使用栈实现的通用括号匹配方法及针对单种括号优化的空间复杂度改进方案。通过具体代码示例,详细解释了算法的实现过程与效率分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

#include<stack>

//{}[]()
//时间复杂度为o(n)空间复杂度为o(n)
bool match(string matchstr)
{
	std::stack<char> m_stak;
	for (int i = 0; i < matchstr.length(); i++) {

		if (matchstr[i] == '(' ||
			matchstr[i] == '[' ||
			matchstr[i] == '{') {

			m_stak.push(matchstr[i]);
			continue;
		}

		if (!m_stak.empty() && (
			(matchstr[i] == ')' && m_stak.top() == '(') ||
			(matchstr[i] == ']' && m_stak.top() == '[') ||
			(matchstr[i] == '}' && m_stak.top() == '{'))) {

			m_stak.pop();
		}
		else {
			return false;
		}
	}

	return m_stak.empty() ? true : false;
}

 对于单一种类的括号,比如只有()括号对,那么算法可以优化,使其空间复杂度变为o(1):

//单括号()
//时间复杂度为o(n)空间复杂度为o(1)
bool singleMatch(string matchstr)
{
	int m_count = 0;
	for (int i = 0; i < matchstr.length(); i++) {

		if (matchstr[i] == '(') {

			m_count++;
			continue;
		}

		if (matchstr[i] == ')') m_count--;
		if (m_count < 0) 
			return false;
	}

	return m_count == 0 ? true : false;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值