題目
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/valid-parentheses
給定一個只包括 '(',')','{','}','[',']' 的字符串,判斷字符串是否有效。
有效字符串需滿足:
左括號必須用相同類型的右括號閉合。
左括號必須以正確的順序閉合。
注意空字符串可被認(rèn)為是有效字符串。
示例 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
}