LeetCode 20. Valid Parentheses

LeetCode 20. Valid Parentheses (有效的括号)

题目

链接

https://leetcode-cn.com/problems/valid-parentheses

问题描述

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

有效字符串需满足:

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

示例

输入: "()"
输出: true

提示

1 <= s.length <= 104
s 仅由括号 '()[]{}' 组成

思路

采用栈,同时增加一个函数用于匹配对应括号。

复杂度分析

时间复杂度 O(n)
空间复杂度 O(1)

代码

Java

    public char match(char c) {
        if (c == ')') {
            return '(';
        }
        if (c == '}') {
            return '{';
        }
        if (c == ']') {
            return '[';
        }
        return c;
    }

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        char[] ch = s.toCharArray();
        for (char c : ch) {
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else {
                if (stack.isEmpty() || stack.peek()!=match(c)) {
                    return false;
                }
                stack.pop();
            }
        }
        if(stack.isEmpty()){
		return true;
        }
        return false;
    }

示例 1:

示例 2:

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

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

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

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

思路

判断括号嘛,我用了最基础的解法,借助栈一个一个找,如果为左括号则入栈,若为右括号且栈顶为对应左括号则出栈,不然直接返回false,一直到遍历结束,如果栈为空就返回true。效率虽然不是很高但是思路很清晰。

posted @ 2020-02-11 22:23  cheng102e  阅读(101)  评论(0编辑  收藏  举报