I am still failing tests for
"negative_match: invalid structures,";"simple_grouped: simple grouped positive and negative test, length=22";"large1 simple large positive test, 100K ('s followed by 100K )'s + )("; and"large2 simple large negative test, 10K+1 ('s followed by 10K )'s + )( + ()".
Can anyone see what my error is? The code I wrote works for all strings I tested...
Here is a description of the task:
A string
Sconsisting ofNcharacters is considered to be properly nested if any of the following conditions is true:
Sis empty;Shas the form"(U)"or"[U]"or"{U}"whereUis a properly nested string;Shas the form"VW"whereVandWare properly nested strings.For example, the string
"{[()()]}"is properly nested but"([)()]"is not.Write a function:
def solution(S)that, given a string
Sconsisting ofNcharacters, returns1ifSis properly nested and0otherwise. For example, givenS = "{[()()]}", the function should return1and givenS = "([)()]", the function should return0, as explained above.Assume that:
Nis an integer within the range[0..200,000];- string
Sconsists only of the following characters:"(","{","[","]","}"and/or")".Complexity: expected worst-case time complexity is
O(N); expected worst-case space complexity isO(N)(not counting the storage required for input arguments).
Here is my solution:
def solution(S):
# write your code in Python 2.7
if S == "":
return 1
length = len(S)
start = 0
end = length-1
if length%2 != 0:
return 0
for i in range(0, length):
if (S[start] == '(') and (S[end] != ')'):
return 0
if (S[start] == '[') and (S[end] != ']'):
return 0
if (S[start] == '{') and (S[end] != '}'):
return 0
start = start +1
end = end -1
return 1
pass
{[()()]}, since at the end you'll be looking at the characters in the middle)(. - Colonel Thirty Two