在Swift中的表达式中检查括号是否平衡

时间:2019-07-17 14:34:17

标签: ios swift

我正在尝试快速编写此代码,因为我找不到任何快速编写的解决方案,但似乎在此实现方面遇到了障碍。 在弹出和推送功能上,我不确定Character是否是正确的返回/参数。

class BalancedParam {
  struct stack {
    var top = -1
    var items = [Character]()

    mutating func push(_ x: Character) {
        items.append(x)
        if top == 99 {
            print("Stack full")
        } else {
            top += 1
            items[top] = x
        }
    }

    mutating func pop() -> Character {
        if top == -1 {
            print("Underflow error")
            return "0"
        } else {
            let element = items[top]
            top -= 1
            return element
        }
    }

    mutating func isEmpty() -> Bool {
        return (top == -1) ? true : false
    }
}

static func isMatchingPair(_ character1: Character, _ character2: Character) -> Bool {
    if character1 == "(" && character2 == ")"  {
        return true
    } else if character1 == "{" && character2 == "}" {
        return true
    } else if character1 == "[" && character2 == "]" {
        return true
    } else {
        return false
    }
}

static func areParenthesisBalanced(_ exp: [Character]) -> Bool {
    // Declare an empty character stack
    var st = stack()
    for i in 0..<exp.count {

        if exp[i] == "{" || exp[i] == "(" || exp[i] == "[" {
                st.push(exp[i])
        }

        if exp[i] == "}" || exp[i] == ")" || exp[i] == "]" {

            if st.isEmpty() {
                return false
            } else if !isMatchingPair(st.pop(), exp[i] ) {
                return false
            }

        }
    }
    if st.isEmpty() {
        return true //balanced
    } else {
        //not balanced
        return false
    }
  }
}

let exp: [Character] = ["{", "(", ")", "}", "[", "]"]
  if BalancedParam.areParenthesisBalanced(exp) {
    print("Balanced ")
  } else {
    print("Not Balanced ")
  }

在理解我做错的事情上,我将不胜感激。谢谢

1 个答案:

答案 0 :(得分:0)

您不能分配给空数组,即items[top] = x,只有在数组大小为top+1或更大的情况下才能使用此语法

所以这不行

var arr = [Int]()
arr[0] = 1

但这是

var arr = [Int]()
arr.append(0)
arr[0] = 1

另一种选择是对数组大小有上限,因此可以初始化该大小的数组,然后继续使用原始语法

var arr = Array(repeating: 0, count: 99)
arr[0] = 1