We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
def isBalanced(s):
stk = []
n = len(s)
for i in range(n):
if s[i] == '{' or s[i] == '[' or s[i] == '(':
stk.append(s[i])
else:
if (stk and ((s[i] == '}' and stk[-1] == '{') or
(s[i] == ']' and stk[-1] == '[') or
(s[i] == ')' and stk[-1] == '('))):
stk.pop()
else:
return "NO" # unmatched closing bracket
if stk:
return "NO"
else:
return "YES"
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Balanced Brackets
You are viewing a single comment's thread. Return to all comments →
def isBalanced(s): stk = [] n = len(s) for i in range(n): if s[i] == '{' or s[i] == '[' or s[i] == '(': stk.append(s[i]) else: if (stk and ((s[i] == '}' and stk[-1] == '{') or (s[i] == ']' and stk[-1] == '[') or (s[i] == ')' and stk[-1] == '('))): stk.pop() else: return "NO" # unmatched closing bracket if stk: return "NO" else: return "YES"