Question: http://codility.com/demo/take-sample-test/nesting
Question Name: Nesting
This question is nearly the same as the previous one, but does not need a stack.
1 2 3 4 5 6 7 8 9 10 11 12 13 | def solution(S): parentheses = 0 for element in S: if element == "(": parentheses += 1 else: parentheses -= 1 if parentheses < 0: return 0 if parentheses == 0: return 1 else: return 0 |
C# solution:
[/crayon]
Adding a Java Solution 100/100:
I am wondering how it passed test case )))(((
It does pass. For the first iteration, parentheses -= 1 and return 0.
100% in javascript
To save time, if the length of the string is odd you can return 0 as it’s impossible to create an even number of pairs.
This is a great catch! That said, in some languages, getting the string length is O(N).