【Leetcode 20】Valid Parentheses

本文介绍了一种使用栈数据结构验证字符串中括号(包括圆括号、方括号和大括号)是否正确匹配的方法。通过遍历字符串,检查每个字符,如果遇到开括号则压入栈中,遇到闭括号则检查栈顶元素是否为相应的开括号,是则弹出,否则返回错误。最后检查栈是否为空,为空则表示括号匹配正确。

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

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

 

题目翻译:

一个string的串,里边放了几种符号 [ ] ( ) { } 要求这些符号合理的组成括号。

需要考虑的边界值 :

[]) 返回false

“” 这种要返回 true

[](){} 这种要返回 true

 

解题思路:

这个思路很简单,使用stack即可,如果stack最上边的符号是(,而新进来的符号是 ) 这样可以弹出stack,括号不配对,就继续压栈。需要注意的是,如果stack是空的,那么stack.top()就会出错,所以,要在判断中加上 !stack.empty() 这样来确定是否出错。

#include <stack>
#include <iostream>
#include <string>


using namespace std;

class Solution {
public:
	bool isValid(string s) {
		int n = s.length();

		stack<char> sta;	
		for (int i = 0; i < n; i++)
		{
			if (s[i] == '}' && !sta.empty() && sta.top() == '{')
			{
				sta.pop();
				continue;
			}
			if (s[i] == ']' && !sta.empty() && sta.top() == '[')
			{
				sta.pop();
				continue;
			}
			if (s[i] == ')' && !sta.empty() &&  sta.top() == '(')
			{
				sta.pop();
				continue;
			}
			sta.push(s[i]);
		}
		if (sta.empty())
			return true;
		else
			return false;

	}
};


int main()
{
	string s;
	getline(cin, s);
	Solution so;
	bool n = so.isValid(s);
	cout << n << endl;

	
	system("pause");
	return 0;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值