Valid Parentheses

Description

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

给出包含三种括号的字符串,验证括号是否左右匹配

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
func isValid(s string) bool {
    var c byte
    stack := make([]byte, 0)
    m := map[byte]byte{
        ')': '(',
        ']': '[',
        '}': '{',
    }
    for i := 0; i < len(s); i++ {
        c = s[i]
        if c == '(' || c == '[' || c == '{' {
            stack = append(stack, c)
        } else {
            if v, ok := m[c]; ok {
                if !pop(v, &stack) {
                    return false
                }
            } else {
                return false
            }
        }
    }

    return len(stack) == 0
}

func pop(c byte, stack *[]byte) bool {
    l := len(*stack)
    if l < 1 {
        return false
    }

    var poped byte
    *stack, poped = (*stack)[:l-1], (*stack)[l-1]

    return poped == c
}

Similar Problem

10. Regular Expression Matching