給定一個只包括 '(',')','{','}','[',']' 的字符串,判斷字符串是否有效。數組
有效字符串需知足:學習
左括號必須用相同類型的右括號閉合。
左括號必須以正確的順序閉合。
注意空字符串可被認爲是有效字符串。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; };