我一直坚持这个很长一段时间,我不能拿出递归的情况下,特别是我不明白如何分割列表来检查它是否平衡。 如果有人能帮助我,我会非常感激。递归检查Python中的平衡字符串
def balanced_str(s):
"""
Return whether string s is balanced or not. A balanced string is one where
the string contains no parentheses
>>> balanced_str('a')
True
>>> balanced_str('abbcsi')
True
>>> balanced_str('ak)')
False
>>> balanced_str('hah(dh')
False
>>> balanced_str('()')
True
>>> balanced_str('(hghghgh)')
True
>>> balanced_str('((a))')
True
>>> balanced_str('((hahsh))')
True
>>> balanced_str('(gfjf)h)')
False
>>> balanced_str('(hhg)(hfhg)')
True
"""
if '(' not in s and ')' not in s:
return True
elif '(' in s and ')' not in s or ')' in s and '(' not in s:
return False
else:
if s[0] == '(' and s[len(s) - 1] == ')':
return balanced_str(s[1:len(s) - 2])
我想你的意思是没有不匹配的圆括号,不是吗? –
@ joelgoldstick是 – jia