我编写了一个示例程序,用于检查括号是否平衡。我试图优化它,这是我能想到的最好的。但是,我想我们是否可以进一步改进这一点。我也不确定这是否是一个有效的问题,可以放在stackoverflow上。任何想法和建议
func checkBalancedParenthesis(parenthesis: String) -> (Bool,String) {
var stack = Stack<Character>()
for character in parenthesis.characters {
guard let check = try? checkValidPattern(a: ("!",character)) else {
return (false,"Pattern is not valid")
}
if let elem = stack.top, try! checkValidPattern(a: (elem,character)) {
stack.pop()
}
else {
stack.push(item: character)
}
}
return (stack.isEmpty,stack.isEmpty ? "Balanced": "Un-Balanced")
}
func checkValidPattern(a: (Character,Character)) throws -> Bool {
let validList: [Character] = ["(",")","[","]","}","{","<",">"]
switch a
{
case ("(",")"):
return true
case ("[","]"):
return true
case ("{","}"):
return true
case ("<",">"):
return true
case let (_,char) where validList.contains(char) == true:
return false
default:
throw InvalidPattern.chracterNotValid
}
}
答案 0 :(得分:1)
可能是我的解决方案对某人有用。检查余额是否有括号,或仅检查括号。 func接受具有匹配字符(或字符串,如果需要)的大小写的字符串和字典,并返回isBalanced(Bool)。 快速3(4)。
对于Swift 4:将“ str.characters”替换为“ str”。
func isBalanced(str: String, dictAccordance: [Character : Character]) -> Bool {
var balArr: [Character] = []
let keys = dictAccordance.keys // all keys (opening characters)
let values = dictAccordance.values // all values (closing characters)
for char in str.characters {
switch char {
// met char from keys. (Met opening character)
case (let key) where keys.contains(char):
balArr.append(key)
// met char from values. (Met closing character)
case (let value) where values.contains(char):
let lastOpenedCharKey = balArr.removeLast() // key of char
// check last matching
if dictAccordance[lastOpenedCharKey] != value {
return false
}
default:
break
}
}
return balArr.isEmpty
}
用法:
override func viewDidLoad() {
super.viewDidLoad()
let dictAccordance: [Character : Character] = [
"(" : ")",
"[" : "]",
"{" : "}",
"<" : ">" // put dict whatever you want
]
let test1 = isBalanced(str: "sdvs", dictAccordance: dictAccordance)
let test2 = isBalanced(str: "()", dictAccordance: dictAccordance)
let test3 = isBalanced(str: "[]<<>>", dictAccordance: dictAccordance)
let test4 = isBalanced(str: "kn(jdnsv;)ds[svds]dvs", dictAccordance: dictAccordance)
let test5 = isBalanced(str: "(dacadc[])", dictAccordance: dictAccordance)
let test6 = isBalanced(str: "([) ewf]", dictAccordance: dictAccordance)
let test7 = isBalanced(str: "[ (()]", dictAccordance: dictAccordance)
let arrTest = [test1, test2, test3, test4, test5, test6, test7]
print(arrTest)
}
答案 1 :(得分:0)
我得到你真正需要的东西。您可以使用for
循环来检查序列中的每个字符。将每个左括号附加到新数组中。对于每个闭合支架,检查新阵列中的最后一个支架是否与关闭支架对应的开口支架,然后卸下开口支架。保持这个直到数组结束,检查数组是否为空。枚举括号以确保类型安全。您可以在代码审核here中查看此链接以获取更多代码。