Check Balanced Parentheses
Python
Medium
4 views
Problem Description
A string s is provided containing only '(' and ')'. Output YES if it is balanced else NO.
Official Solution
import sys
s=sys.stdin.read().strip()
if not s: sys.exit(0)
bal=0
ok=True
for ch in s:
if ch=='(':
bal+=1
else:
bal-=1
if bal<0:
ok=False
break
if bal!=0:
ok=False
sys.stdout.write('YES' if ok else 'NO')
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!