有效的括号

有效的括号

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

  1. 左括号必须用相同类型的右括号闭合

  2. 左括号必须以正确的顺序闭合

  3. 注意空字符串可被认为是有效字符串

package leetcode;

import java.util.Stack;

/***
 * [20] 有效的括号
 */
public class ValidSolution {
    public boolean  isValid(String s){
        if(s == null || s.length() == 0){
            return true;
        }
        if(s.length() % 2 == 1){
            return false;
        }
        Stack<Character> t = new Stack<Character>();
        for(int i= 0 ; i <s.length() ; i++){
            char c= s.charAt(i);
            if (c == '(' || c == '[' || c =='{') {
                t.push(c);
            }else if(c == ')'){
                if(t.empty() || t.peek() != '('){
                    return false;
                }
                t.pop();
            }else if(c == ']'){
                if(t.empty() || t.peek() != '['){
                    return false;
                }
                t.pop();
            }else if(c == '}'){
                if(t.empty() || t.peek() != '{'){
                    return false;
                }
                t.pop();
            }else{
                return false;
            }
        }
        return t.empty();
    }
    public static void main(String[] args){
        ValidSolution vs = new ValidSolution();
        boolean a = vs.isValid("([{)}]");
        boolean b=  vs.isValid("([{}])");
        System.out.println(a);
        System.out.println(b);
    }
}

 

posted on 2021-05-16 19:06  凌晨三点半的飞机  阅读(38)  评论(0编辑  收藏  举报