LeetCode20:validParentheses

validParentheses

題目描述

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

An input string is valid if:java

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:app

Input: "()" Output: true Example 2:ide

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

Input: "(]" Output: false Example 4:blog

Input: "([)]" Output: false Example 5:ip

Input: "{[]}" Output: true字符串

思路

  • 使用棧方法,遍歷字符串
  • 若是當前字符爲左邊括號時,直接將其壓入棧
  • 若是遇到右半邊括號時,分類討論:
    • 1.若是棧不爲空,驗證是否對應左邊的括號,取出棧頂元素,繼續循環、
    • 若這時棧爲空,則直接返回false
    • 若不爲對應的左邊括號,返回false

實現思路

1.使用棧方法(使用數組的push()和pop()來模擬)input

代碼

var isValid = function(s) {
  let valid = true
  const stack = []
  const mapper = {
    '{': '}',
    '(': ')',
    '[': ']'
  }
  if (s === '') {
    return valid;
  }
  for (let value of s) {
    let v = value;
    if (['{', '(', '['].indexOf(v) != -1) {
      stack.push(v)
    } else {
      if (stack.length == 0) {
        valid = false;
      } else {
        const va = stack.pop()
        if (mapper[va] != v) {
          valid = false;
        }
      }
    }
  }
  return valid;
}
相關文章
相關標籤/搜索