首页 > Web开发 > 详细

20. Valid Parentheses(js)

时间:2019-02-16 13:23:45      阅读:344      评论:0      收藏:0      [点我收藏+]

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
题意:判断多个括号组是否有效
代码如下:
/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    var arr=[];
    var len=s.length;
    for(var i=0;i<len;i++){
        if(s.charAt(i)=="{"){
            arr.push(‘}‘)
        }else if(s.charAt(i)==‘[‘){
            arr.push(‘]‘);
        }else if(s.charAt(i)==‘(‘){
            arr.push(‘)‘);
        }else{
            if(arr.length==0 || arr.pop() !=s.charAt(i)){
                return false;
            }
        }
    }

    return arr.length===0?true:false;
};

 

20. Valid Parentheses(js)

原文:https://www.cnblogs.com/xingguozhiming/p/10387356.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!