私はかなり長い間、この問題に悩まされていました。再帰的なケースを思いつくことはできません。特にバランスのとれた場合にリストを分割する方法を理解できません。 誰かが私を助けることができたら、私は本当にそれを感謝します。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