美文网首页
leetcode:20. Valid Parentheses

leetcode:20. Valid Parentheses

作者: 唐僧取经 | 来源:发表于2018-08-17 09:02 被阅读0次

20. Valid Parentheses

Description

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

An input string is valid if:

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:

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

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

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

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

Input: "{[]}"
Output: true

Answer


package main

import "fmt"

func isValid(s string) bool {

    arr := make([]byte, 0, len(s))

    for i := 0; i < len(s); i++ {

        if s[i] == '(' || s[i] == '[' || s[i] == '{' {
            arr = append(arr, s[i])
            continue
        }

        if s[i] == ')' || s[i] == ']' || s[i] == '}' {
            if len(arr) == 0 {
                return false
            }
            if s[i] == ')' && arr[len(arr)-1] == '(' {
                arr = arr[0:len(arr)-1]
                continue
            }

            if s[i] == ']' && arr[len(arr)-1] == '[' {
                arr = arr[0:len(arr)-1]
                continue
            }

            if s[i] == '}' && arr[len(arr)-1] == '{' {
                arr = arr[0:len(arr)-1]
                continue
            }
            return false

        }

    }
    if len(arr) == 0 {
        return true
    } else {
        return false
    }

}

func main() {

    arr := "()[]{[}"
    fmt.Println(isValid(arr))
}


相关文章

网友评论

      本文标题:leetcode:20. Valid Parentheses

      本文链接:https://www.haomeiwen.com/subject/ssfzbftx.html