Java determines whether the given string is a legal bracket sequence

Title description

Given a string containing only the characters'(',')','{','}','[' and']', determine whether the given string is a legal bracket sequence. The
brackets must be correct The order is closed, "()" and "()[]{}" are both legal bracket sequences, but "(]" and "([)]" are illegal.

Example 1

enter

"["

return value

false

Example 2

enter

"[]"

return value

true
import java.util.*;


public class Solution {
    /**
     * 有效的括号
     * <p>
     * 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
     * 有效字符串需满足:
     * 左括号必须用相同类型的右括号闭合。
     * 左括号必须以正确的顺序闭合。
     * 注意空字符串可被认为是有效字符串。
     * 示例 1:
     * 输入: "()"
     * 输出: true
     * 示例 2:
     * 输入: "()[]{}"
     * 输出: true
     * 示例 3:
     * 输入: "(]"
     * 输出: false
     * 示例 4:
     * 输入: "([)]"
     * 输出: false
     * 示例 5:
     * 输入: "{[]}"
     * 输出: true
     */
    public boolean isValid (String s) {
        
        if(s==null || s.length()==0){
            return true;
        }
        
        Stack<Character> stack = new Stack<Character>();
        char[] chars = s.toCharArray();
        for(int i=0;i<chars.length;i++){
            if('[' == chars[i]){
                stack.push(']');
            }else if('{' == chars[i]){
                 stack.push('}');
            }else if('(' == chars[i]){
                 stack.push(')');
            }else if(stack.isEmpty() || stack.pop()!=chars[i]){//if  else if只能走一个分支
                return false;
            }
        }
        
        //都弹出完了 才算全部匹配
        return stack.isEmpty();
    }
}

 

Guess you like

Origin blog.csdn.net/luzhensmart/article/details/112758715