leetcode 20. 有效的括号

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

有效字符串需知足:学习

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

示例 1:prototype

输入: "()" 输出: true

示例 2:code

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

示例 3:element

输入: "(]" 输出: false

示例 4:字符串

输入: "([)]" 输出: false

示例 5:io

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

解题思路:碰见匹配的问题,最好的解决方案就是Stack结构,可是JS自己是没有栈结构的,JS能够用数组来实现栈,本着学习的目的,咱们本身实现一个栈结构来解决该问题。function

function Stack() {
    this.dataStore = [];
    this.top = 0;  //记录栈顶位置
}
//压栈操做
Stack.prototype.push = function(element) {
    this.dataStore[this.top++] = element;//压入元素后将top加1
}
//出栈操做
Stack.prototype.pop = function() {
    return this.dataStore[--this.top];//取出元素后将top减1
}
//返回栈顶元素
Stack.prototype.peek = function() {
    return this.dataStore[this.top-1];
}
//返回栈的长度
Stack.prototype.length = function() {
    return this.top;
}
//清空栈
Stack.prototype.clear = function() {
    this.top = 0;
}
var isValid = function(s) {
    var stack = new Stack();
    for(var i = 0; i<s.length; i++){
        //碰到左括号,push右括号
        if(s[i] === "(") {
            stack.push(")");
        } else if(s[i] === "[") {
            stack.push("]");
        } else if(s[i] === "{") {
            stack.push("}");
        } else{
        //不是左括号,判断栈是否为空或栈顶元素是否等当前元素
            if(!stack.top || stack.peek() != s[i]){
                return false
            }else{
                stack.pop()
            }
        } 
    }
    return !stack.top;
};
相关文章
相关标签/搜索