Leetcode题目20.有效的括号(简单)

题目描述:

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

有效字符串需满足:

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

示例 1:

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

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

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

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

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

题目解析:

使用LinkedList作为辅助栈:

  • 遍历输入字符串
  • 如果当前字符为左半边括号时,则将其压入栈中
  • 如果遇到右半边括号时,分类讨论:
  • 1)如栈不为空且为对应的左半边括号,则取出栈顶元素,继续循环
  • 2)若此时栈为空,则直接返回false
  • 3)若不为对应的左半边括号,反之返回false

代码实现:

package com.company;

import java.util.LinkedList;

public class Main {

    public static void main(String[] args) {
        String str = "]";
        System.out.println(isValid(str));
    }

    private static boolean isValid(String s) {
        if (s == null || s.isEmpty()) {
            return true;
        }
        LinkedList<Character> linkedList = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == '(' || ch == '[' || ch == '{') {
                linkedList.add(ch);
            } else {
                //栈中没有元素,而当前符号为右括号,直接返回false,当前符号也不需要进栈
                if (linkedList.isEmpty()) {
                    return false;
                }
                if (ch == ')') {
                    if (linkedList.peekLast() != '(') {
                        return false;
                    }
                }
                if (ch == ']') {
                    if (linkedList.peekLast() != '[') {
                        return false;
                    }
                }
                if (ch == '}') {
                    if (linkedList.peekLast() != '{'){
                        return false;
                    }
                }
                if (!linkedList.isEmpty()) {
                    linkedList.removeLast();
                }
            }
        }
        return linkedList.isEmpty();
    }
}

时间复杂度:O(N),遍历一遍,n为str的长度大小

空间复杂度:O(N),LinkedList的大小n,也就是辅助栈的大小

原文地址:https://www.cnblogs.com/ysw-go/p/11765463.html