我仍然没有通过测试
"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 + )("
;以及"large2 simple large negative test, 10K+1 ('s followed by 10K )'s + )( + ()"
。在有人能看出我的错误是什么吗?我写的代码适用于我测试的所有字符串。。。在
以下是任务说明:
A string
S
consisting ofN
characters is considered to be properly nested if any of the following conditions is true:
S
is empty;S
has the form"(U)"
or"[U]"
or"{U}"
whereU
is a properly nested string;S
has the form"VW"
whereV
andW
are properly nested strings.For example, the string
"{[()()]}"
is properly nested but"([)()]"
is not.Write a function:
def solution(S)
that, given a string
S
consisting ofN
characters, returns1
ifS
is properly nested and0
otherwise. For example, givenS = "{[()()]}"
, the function should return1
and givenS = "([)()]"
, the function should return0
, as explained above.Assume that:
N
is an integer within the range[0..200,000]
;- string
S
consists 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).
我的解决方案是:
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
您正在从从左到右和从右到左-这将在^{上失败-即使它是有效的,因为您会将}进行比较。(})
[
与{start = 1
和{作为口头描述,我将做以下几点:
示例:给定的字符串是
{([])]
。在[
,{
,(
将期望的右括号放在期望字符串的末尾。i、 例如]
,}
或{它会像这样处理给定的字符串:
^{pr2}$编辑:由于预期的“存储复杂性”也是
Oh(n)
(不计算输入参数),所以当给定的字符串有n
的左括号时,您将恰好遇到Oh(n)
的存储复杂性,这没问题。但你是ofc。应该使用第二个string
,那么原因列表有开销。在对于运行时的复杂性:
Oh(1)
(表示常量)if()
语句是原子的->;Oh(1)
(表示常量)Oh(1)
(表示常量)Oh(n)
(取决于n)总结一下,你会得到
Oh(n)
。在如果您想在Python中实现这一点,可以使用http://dog-net.org/string.php来验证您的“步骤”。:-)
注:我不是故意提供复制和粘贴解决方案!:P
相关问题 更多 >
编程相关推荐