• 20. 有效的括号


    一、题目

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

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

    有效字符串需满足:

    1、左括号必须用相同类型的右括号闭合
    2、左括号必须以正确的顺序闭合

    示例 1:

    输入: "()"
    输出: true

    示例 2:

    输入: "()[]{}"
    输出: true

    示例 3:

    输入: "(]"
    输出: false

    示例 4:

    输入: "([)]"
    输出: false

    示例 5:

    输入: "{[]}"
    输出: true

    二、思路及解法

    此题类似于寻找对称的字符,此处可以用栈来处理

    1、遍历字符串,先让左括号入栈
    2、当遍历到右边符号时,先判断栈顶元素是否为对应的左括号,如果不是,则返回false
    3、如果是对应的左括号,则左括号出栈
    4、继续遍历,直到栈为空,则返回true

    public class N20 {
    
    	public static void main(String[] args) {
    		String s = "()[]{}";
    		s = "{()[]}";
    		System.out.println(isValid(s));
    	}
    	
    	public static boolean isValid(String s) {
    		Stack<Character> stack = new Stack<Character>();
    		if(s.length() % 2 != 0){
    			return false;
    		}
    		for(int i = 0 ; i < s.length() ; i++){
    			char c = s.charAt(i);
    			if(c == '(' || c == '[' || c == '{'){
    				stack.push(c);
    			}else{
    				if(stack.isEmpty()){
    					return false;
    				}
    				if(c == ')' && stack.peek() != '('){
    					return false;
    				}
    				if(c == ']' && stack.peek() != '['){
    					return false;
    				}
    				if(c == '}' && stack.peek() != '{'){
    					return false;
    				}
    				stack.pop();
    			}
    		}
    		return stack.isEmpty();
    	}
    
    }
    
  • 相关阅读:
    IfcFurnishingElementType
    IfcRelAssociatesClassification
    IfcRelAssociatesDocument
    IfcContext
    IfcRelAssociatesMaterial
    我是高敏感的人,你呢?
    介绍一本红色的书
    矫枉必须过正
    大家都在说的民法典,与我有何关系?
    线上Kafka突发rebalance异常,如何快速解决?
  • 原文地址:https://www.cnblogs.com/lmj612/p/12891243.html
Copyright © 2020-2023  润新知