[LeetCode] 20. Valid Parentheses

原题链接:https://leetcode.com/problems/valid-parentheses/

1. 题目介绍

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

An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
给出一个字符串,包含 ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ 和 ‘]’ 这六种字符。判断字符串中的括号是否是匹配的。

  1. 如果有一个左括号,之后必须有一个同类型的右括号。
  2. 括号关闭的顺序不能乱。
  3. 一个空的字符串也被看作是合法的。

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

2. 解题思路

这样的括号匹配的题目,使用堆栈来解决的可能性非常大。设置一个堆栈,堆栈中只存放所有的左括号。
从头遍历字符串,如果遇到的字符是 ‘(’, ‘[’, ‘{’ 这三种左括号的话,就将它们存入堆栈。

如果遇到 ‘)’, ‘]’ ,’}’ 这三种右括号。就需要把当前的字符和堆栈顶部的左括号进行比对,如果右括号和栈顶左括号匹配的话,就弹出栈顶元素;否则就返回 false。

如果所有的括号都被匹配了,那么堆栈将变为空。如果遍历完字符串后,堆栈还没有空,那就是左括号多了,同样返回false。

实现代码

class Solution {
    public boolean isValid(String s) {
		int length = s.length();
		Stack<Character> sta = new Stack<Character>();
		for (int i = 0; i<length ; i++) {
			char a = s.charAt(i);

			if (a == '(' || a == '[' || a == '{') {
				sta.push(a);

			}else {
                if(sta.empty() == true){
                    return false;
                }
				char b = sta.peek();
				if (a == ')' && b == '(') {
					sta.pop();
				}else if (a == ']' && b == '[') {
					sta.pop();
				}else if (a == '}' && b == '{') {
					sta.pop();
				}else{
					return false;
				}
			}
		}
        
        return (sta.empty() == true ? true : false);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值