给定一个字符串A和其长度n,请返回一个bool值代表它是否为一个合法的括号串(只能由括号组成)。
测试样例:
"(()())",6
返回:true
测试样例:
"()a()()",7
返回:false
测试样例:
"()(()()",7
返回:false
class Parenthesis:
def chkParenthesis(self, A, n):
# write code here
stack=[]
for i in A:
if i=="(":
stack.append("(")
elif i==")":
if not stack:return False
stack.pop()
return stack==[]
# -*- coding:utf-8 -*-
class Parenthesis:
def chkParenthesis(self, A, n):
if n <= 0:
return False
a = list(A)
left = a.count('(')
right = a.count(')')
if left != right or left + right != n:
return False
b = []
def check(b):
if not b:
return True
tmp = b[:]
idx = 0
flag = False
for i, j in zip(tmp, tmp[1:]):
if i == '(' and j == ')':
flag = True
b[idx] = ''
b[idx + 1] = ''
idx += 1
if flag == False:
return False
else:
b = [i for i in b if i != '']
return check(b)
return check(b)
# -*- coding:utf-8 -*-
class Parenthesis:
def chkParenthesis(self, A, n):
a = list(A)
stack = []
for i in a:
if i == '(':
stack.append(i)
elif i == ')':
if not stack:
return False
else:
stack.pop()
else:
return False
return True