Skip to content

Instantly share code, notes, and snippets.

@Mindstormer619
Created January 17, 2017 18:02
Show Gist options
  • Save Mindstormer619/5fc6c558138546fd90fc3c5bfdeec023 to your computer and use it in GitHub Desktop.
Save Mindstormer619/5fc6c558138546fd90fc3c5bfdeec023 to your computer and use it in GitHub Desktop.
r/dailyprogrammer Challenge #298 [Easy] Solution
exp = raw_input()
# assuming exp is balanced
stack = []
justClosed = False # did we just close a paren in the last operation
for ch in exp:
if ch != ')':
stack.append(ch)
justClosed = False
else:
poppedItems = []
lastItem = stack.pop()
while lastItem != '(':
poppedItems.append(lastItem)
lastItem = stack.pop()
if justClosed == True and len(poppedItems) == 1:
stack.append(poppedItems[0])
elif len(poppedItems) == 0:
pass # put nothing to the stack
else:
poppedItems.reverse()
stack.append('(' + ''.join(poppedItems) + ')')
justClosed = True
print ''.join(stack)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment