• [LeetCode] 20. Valid Parentheses


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

    An input string is valid if:

    1. Open brackets must be closed by the same type of brackets.
    2. 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

    有效的括号。

    题意是给一个input,请判断他是否是一组有效的括号。思路是用stack做。如果看到左半边括号就无条件压入栈;如果看到右半边括号,判断栈是不是为空,为空就报错;栈不为空再判断目前栈顶元素是不是相对应的左半边,若不是也报错。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public boolean isValid(String s) {
     3         Deque<Character> stack = new ArrayDeque<>();
     4         for (char c : s.toCharArray()) {
     5             if (c == '(' || c == '[' || c == '{') {
     6                 stack.push(c);
     7             }
     8             if (c == ')') {
     9                 if (stack.isEmpty() || stack.pop() != '(') return false;
    10             }
    11             if (c == ']') {
    12                 if (stack.isEmpty() || stack.pop() != '[') return false;
    13             }
    14             if (c == '}') {
    15                 if (stack.isEmpty() || stack.pop() != '{') return false;
    16             }
    17         }
    18         return stack.isEmpty();
    19     }
    20 }

    JavaScript实现

     1 /**
     2  * @param {string} s
     3  * @return {boolean}
     4  */
     5 var isValid = function(s) {
     6     let stack = [];
     7     for (let i = 0; i < s.length; i++) {
     8         if (s[i] === '(' || s[i] === '[' || s[i] === '{') {
     9             stack.push(s[i]);
    10         }
    11         if (s[i] === ')') {
    12             if (stack.length === 0 || stack.pop() != '(') return false;
    13         }
    14         if (s[i] === ']') {
    15             if (stack.length === 0 || stack.pop() != '[') return false;
    16         }
    17         if (s[i] === '}') {
    18             if (stack.length === 0 || stack.pop() != '{') return false;
    19         }
    20     }
    21     return stack.length === 0 ? true : false;
    22 };

    相关题目

    20. Valid Parentheses

    678. Valid Parenthesis String

    1111. Maximum Nesting Depth of Two Valid Parentheses Strings

    921. Minimum Add to Make Parentheses Valid

    1541. Minimum Insertions to Balance a Parentheses String

    LeetCode 题目总结

  • 相关阅读:
    rails3 routes
    rails delete destroy difference
    ruby doc
    今天提交了一个patch开心,呵呵
    ruby collect map seems the function is the same?
    jquery closest
    rails 笔记
    网店系统
    rails脚本架命令及心得
    rails3 expericence
  • 原文地址:https://www.cnblogs.com/cnoodle/p/11651581.html
Copyright © 2020-2023  润新知