[LeetCode]20 有效的括号

刚好最近在用java复习数据结构,现学现用(感觉自己在刷水题的快乐里无法自拔hh)

题目描述

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

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true
示例 2:

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

输入: "(]"
输出: false
示例 4:

输入: "([)]"
输出: false
示例 5:

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

  

思路:

这种匹配的,一般都是用栈,比如之前做过的表达式类型的题,都是一个道理

把字符串分成一个个字符,再遍历,如果当前遍历的字符没能和栈顶元素匹配,则入栈,如果能,则将与之匹配的元素出栈

最后,检查栈里是否还有元素,如果有,代表没有完全匹配,返回false,如果有,则代表全都匹配了.返回true;

代码:

public class Main {
    public static void main(String[] args) throws Exception{
        System.out.println(isValid("[])"));
    }
    public static boolean isValid(String s){

        if (s==null||s.length()==0){
            return true;
        }
        SqStack stack = new SqStack(s.length());
        boolean is = false;
        for (int i = 0;i < s.length();i++){
            char ch = s.charAt(i);
            if (stack.isEmpty()){
                stack.push(ch);
            }else {
                if(ch==')'&&stack.peek()=='('){
                    stack.pop();
                }else if (ch==']'&&stack.peek()=='['){
                    stack.pop();
                }else if(ch=='}'&&stack.peek()=='{'){
                    stack.pop();
                } else {
                    stack.push(ch);
                }
            }
            if (stack.isEmpty()){
                is = true;
            }else {
                is = false;
            }
        }
        return is;
    }

}

  

这是自己写的栈的类

/**
 * 顺序栈
 * */
public class SqStack {
    //栈的大小
    private int maxSize;
    //栈顶指针
    private int top;

    private char[] stack;

    public SqStack(int size){
        maxSize = size;
        top = -1;
        stack = new char[maxSize];
    }
    //压栈
    public void push(char value){
        stack[++top] = value;
    }
    //出栈
    public char pop(){
        return stack[top--];
    }
    //返回栈顶指针
    public char peek(){
        return stack[top];
    }
    //栈是否满
    public boolean idFull(){
        return maxSize-1==top;
    }
    //栈是否为空
    public boolean isEmpty(){
        return top==-1;
    }
}

  

最后好像速度还行,之前没有把debug的打印语句注释掉导致速度67ms直接爆炸,去掉之后5ms

原文地址:https://www.cnblogs.com/Yintianhao/p/9979550.html