Algorithms: Matching Parenthesis Problem in Swift

Subscribe to my newsletter and never miss my upcoming articles

Hey folks Leo here, This is a classic algorithm problem and the solution is very straightforward. The problem:

Given a string of parenthesis ‘(‘ and ‘)’, write a function which returns true if there are matching pairs and false if there are not. A matching pair means, there should be a closing parenthesis for an opening one, in correct order.

The easiest solution is using a stack data structure. Check the solution below:

func isMatchinParenthesis(phrase: String) -> Bool {
    var resultStack : [String.Element] = []
    if phrase.isEmpty || phrase.count < 2 {
        return false
    }
    for letter in phrase {
        if letter == "(" {
            resultStack.append(letter)
        } else if letter == ")" {
            if resultStack.last == "(" {
                resultStack.popLast()
            } else {
                return false
            }
        }
    }
    return resultStack.isEmpty
}

You can use switch statement rather than the if's. There are others ways to accomplish this, can you find another one?

Thanks for reading, That's all folks!

No Comments Yet