利用栈解决括号匹配问题

遍历字符串,遇到左括号,入栈。遇到有括号,出栈。遍历完后,如果栈中还有元素就说明括号不匹配,否则匹配。

/// 利用栈解决括号匹配问题
    private func isMach(str: String) -> Bool {
        var stack = Stack()
        for char in str.enumerated() {
            let s = char.element
            if s == "(" {
                stack.push(item: s)
            } else if s == ")" {
                let item = stack.pop()
                if item == nil {
                    return false
                }
            }
        }
        if stack.isEmpty() {
            return true
        } else {
            return false
        }
    }

demo地址:https://github.com/yangguanghei/studyDateStructure

你可能感兴趣的:(利用栈解决括号匹配问题)