leetcode:20. Valid Parentheses

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)