leetcode: 有效的括号

2019-06-16  本文已影响0人  简书帅气的昵称已被使用

题目

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses

给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true
示例 2:

输入: "()[]{}"
输出: true
示例 3:

输入: "(]"
输出: false
示例 4:

输入: "([)]"
输出: false
示例 5:

输入: "{[]}"
输出: true

解法

func isValid(s string) bool {
    a := map[string]string{
        "[": "]",
        "]": "[",
        "{": "}",
        "}": "{",
        "(": ")",
        ")": "(",
    }

    if len(s)%2 != 0 {
        return false
    }

    listInfo := list.New()

    for _, value := range s {
        valueStr := string(value)

        if listInfo.Len() == 0 {
            listInfo.PushBack(valueStr)
            continue
        }

        topElement := listInfo.Back()
        topElementValue := topElement.Value

        if topElementValue == a[valueStr] {
            listInfo.Remove(topElement)
            continue
        }

        listInfo.PushBack(valueStr)
    }

    if listInfo.Len() == 0 {
        return true
    }

    return false
}
上一篇下一篇

猜你喜欢

热点阅读