Solution to Brackets by codility
Question: http://codility.com/demo/take-sample-test/brackets Question Name: Brackets Classic application of stacks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | def solution(S): if len(S) % 2 == 1: return 0 matched = {"]":"[", "}":"{", ")": "("} to_push = ["[", "{", "("] stack = [] for element in S: if element in to_push: stack.append(element) else: if len(stack) == 0: return 0 elif matched[element] != stack.pop(): return 0 if len(stack) == 0: return 1 else: return 0 |
UPDATE (2016-07-19): Much appreciate Jeffrey’s comment and suggestion: I’m surprised so few people didn’t do a simple modulo at the start to check whether there is an even number of chars. … Read More »