【Codewars】判断括号是否有效 validParentheses

题目描述:Write a function called validParentheses that takes a string of parentheses, and determines if the order of the parentheses is valid. validParentheses should return true if the string is valid, and false if it's invalid.


中文描述:写一个叫"validParentheses"(即有效的括号)的函数,接受一个string格式变量的包含括号的参数,判断括号的顺序(包括数量)来判断括号是否有效。有效返回true,无效返回false.


Examples: 
validParentheses( "()" ) => returns true 
validParentheses( ")(()))" ) => returns false 
validParentheses( "(" ) => returns false 
validParentheses( "(())((()())())" ) => returns true 


以下提供两种解法(用的是Python实现):

1. -------->提取所有的括号(),在用string.replace()的方法,看最后是不是能提取完


def valid_parentheses(string):
    a = []
    for i in string:
        if i == '(' or i == ')':
            a.append(i)
    a = ''.join(a)
    while(True):
        b = a
        a = a.replace('()','')
        if a == b:
            break
    if a == '':
        return True
    else:
        return False


2.可以注意到第一个括号必须是要左括号“(”,最后一个括号必须是要“)”,而两个括号的数量必须相等,所以聪明的同学可能已经想到了使用带符号数来量化这一过程啦!以下是代码:

def valid_parentheses(string):
    cnt = 0
    for char in string:
        if char == '(': cnt += 1
        if char == ')': cnt -= 1
        if cnt < 0: return False
    return True if cnt == 0 else False


这次的节目就到这里,谢谢大家!


你可能感兴趣的:(【Codewars】判断括号是否有效 validParentheses)