Enesxg
Enesxg

Reputation: 127

How to check if inputted parentheses are valid

Is there an efficient method to find out if a string input uses correctly?

So, "((()))()" is correct. "()()(" is incorrect. "hi())(" is incorrect.

I have tried this:

def valid_parentheses(string): 
    utilList = [] for i in string:     
        utilList.append(i)
    open = utilList.count("(")
    close = utilList.count(")")
    if (open + close) % 2 == 0:
        return True
    else:
        return False

Upvotes: 0

Views: 149

Answers (2)

Michael Stroud
Michael Stroud

Reputation: 279

Use a variable to track the parentheses nesting level. It starts at 0.

Iterate through the string. Each time you reach an open parenthesis, add 1 the nesting level. Subtract 1 each time you reach a closing parenthesis.

If the number is ever negative, or if the number is not zero when you reach the end of the string, then the parentheses are malformed.

Upvotes: 0

Bill the Lizard
Bill the Lizard

Reputation: 405955

You can just loop through your text and keep count. +1 for (, -1 for ). At the end of the loop, the counter should be 0. If the counter ever goes negative, you can exit early knowing that they are not balanced.

Upvotes: 1

Related Questions