Blog.

有效的括号

Cover Image for 有效的括号
Bernie
Bernie

20. 有效的括号

leetcode 链接

思路:

1.使用一个栈存储遍历到的字符,如果当前字符和栈顶字符匹配,则弹出栈顶字符,否则将当前字符入栈。

typescript 解法

function isValid(s: string): boolean {
  let stack: string[] = [];
  const arr: string[] = s.split("");
  const length: number = s.length;
  for (let i: number = 0; i < length; i++) {
    let top: string = stack.length != 0 ? stack[stack.length - 1] : "";
    const current: string = arr[i];
    if (
      (top === "[" && current === "]") ||
      (top === "{" && current === "}") ||
      (top === "(" && current === ")")
    ) {
      stack.pop();
    } else {
      stack.push(current);
    }
  }
  return stack.length === 0;
}

go 解法

func isValid(s string) bool {
    stack := make([]string, 0)
    for i := 0; i < len(s); i ++ {
        top := ""
        if len(stack) != 0 {
            top = stack[len(stack) - 1]
        }
        current := string(s[i])
        if (top == "(" && current == ")") || (top == "[" && current == "]") || (top == "{" && current == "}") {
            stack = stack[:len(stack) - 1]
        } else {
            stack = append(stack, current)
        }
    }
    return len(stack) == 0
}