20. Valid Parentheses

栏目: Java · 发布时间: 6年前

内容简介:Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.An input string is valid if:Open brackets must be closed by the same type of brackets.

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.

Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:
Input: "()"
Output: true

Example 2:
Input: "()[]{}"
Output: true

Example 3:
Input: "(]"
Output: false

Example 4:
Input: "([)]"
Output: false

Example 5:
Input: "{[]}"
Output: true

难度:easy

题目:

给定仅包含字符'(', ')', '{', '}', '[' 和 ']'的字符串, 判定这个字符串是否有效。

输入字符串是否有效:

开括号必需与同类型括号关闭。

开括号必需要以正确的顺序关闭。

注意 空字符串被认为是有效的字符串。

思路:stack

Runtime: 5 ms, faster than 74.68% of Java online submissions for Valid Parentheses.

Memory Usage: 26.3 MB, less than 52.20% of Java online submissions for Valid Parentheses.

class Solution {
    public boolean isValid(String s) {
        // stack
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                stack.push(')');
            } else if (c == '{') {
                stack.push('}');
            } else if (c == '[') {
                stack.push(']');
            } else {
                if (stack.isEmpty() || stack.pop() != c) {
                    return false;
                }
            }
        }
        
        return stack.isEmpty();
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

任性

任性

电子工业出版社 / 2015-10-1 / 49.00

《任性:互联网语言表达的调性和技巧》是一本深度介绍互联网调性的书,也是从社会化媒体运作的角度较为系统地讲解互联网语言表达的书,它以独特的视角,从技术、需求和表现形式三种驱动力展开,从理论、策略、方法、技巧、实践等角度详细解析了互联网表达的变化和社会媒体的运营。《任性:互联网语言表达的调性和技巧》适合互联网从业人员阅读。一起来看看 《任性》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具