我的leetcode做题记录 leetcode 20: Valid Parentheses

本文介绍了一种使用栈数据结构来验证括号序列有效性的方法。通过遍历输入字符串,将左括号压入栈中,并在遇到右括号时检查栈顶元素是否为匹配的左括号。最后确保栈为空以确认括号序列的有效性。

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

Leetcode 20. Valid Parentheses

Given a string s 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.

Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

Example 4:

Input: s = "([)]"
Output: false

Example 5:

Input: s = "{[]}"
Output: true

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

Solution(java): 

class Solution {
    public boolean isValid(String s) {
        char[] symbol = {'(' , ')' , '{' , '}' , '[' , ']' };
        int len = s.length();
        if(len%2 != 0 ) return false;
        
        Stack<Character> parentheses= new Stack<Character>();
        
        for(int i = 0 ; i<s.length(); i++){
            if (s.charAt(i) == symbol[0]) parentheses.push(s.charAt(i));
            if (s.charAt(i) == symbol[2]) parentheses.push(s.charAt(i));
            if (s.charAt(i) == symbol[4]) parentheses.push(s.charAt(i));
            
            if (parentheses.empty()) return false;
           else if (s.charAt(i) == symbol[1] ) {
                if (parentheses.peek() !=symbol[0] ) return false;
                else parentheses.pop();
            }
           else if (s.charAt(i) == symbol[3]) {
                if (parentheses.peek() !=symbol[2] ) return false;
                else parentheses.pop();
            }
           else if (s.charAt(i) == symbol[5]) {
                if (parentheses.peek() !=symbol[4] ) return false;
                else parentheses.pop();
            }
        }
        return parentheses.empty();
        
    }
}

使用栈来解决该问题:

栈的特点: 后进先出

如遇到左半边括号:放入栈中。

如遇到右半边括号:若此时栈为空(parentheses.empty() ),则return false.

                                否则,判断栈顶元素(parentheses.peek())与当前括号是否匹配,若匹配,则继续循环。若不匹配,则return false.

最后判断栈是否为空,若栈为空,则该问题为true。 

 

参考资料:

https://leetcode.com/problems/valid-parentheses/

https://www.cnblogs.com/grandyang/p/4424587.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值