0

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
cookiedough
  • 3,552
  • 2
  • 26
  • 51
Enesxg
  • 127
  • 4
  • 13

2 Answers2

1

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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
0

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.

Michael Stroud
  • 279
  • 1
  • 2