題目: 給定一個只包括 '(',')','{','}','[',']' 的字符串,判斷字符串是否有效。
有效字符串需滿足:
左括號必須用相同類型的右括號閉合。
左括號必須以正確的順序閉合。
注意空字符串可被認為是有效字符串。
**例如: **
輸入: "()"
輸出: true
輸入: "()[]{}"
輸出: true
輸入: "(]"
輸出: false
輸入: "([)]"
輸出: false
棧方法
使用「?!惯@一數(shù)據(jù)結(jié)構來解決。
1.首先有效括號一定是相同類型左右閉合, 即偶數(shù), 所以奇數(shù)先排除
2.for循環(huán)判斷, 左括號依次入棧
3.由于括號需要相同類型閉合, 所以依次判斷右括號是否棧頂依次配對, 配對出棧, 不匹配彈出返回false
4.循環(huán)結(jié)束判斷棧中元素是否為0
func isValid(_ s: String) -> Bool {
if s.count % 2 != 0 {
return false
}
var temp: [Character] = []
for i in s {
switch i {
case "(", "[", "{":
temp.append(i)
case ")":
if temp.last != "(" {
return false
}
temp.removeLast()
case "]":
if temp.last != "[" {
return false
}
temp.removeLast()
case "}":
if temp.last != "{" {
return false
}
temp.removeLast()
default:
break
}
}
if temp.count != 0 {
return false
}
return true
}
題目來源:力扣(LeetCode) 感謝力扣爸爸 :)
IOS 算法合集地址