请查看我的 Python 递归片段

-1 python recursion

问题:

给定一个字符串 S,递归计算一个新字符串,其中原始字符串中相邻的相同字符用“*”彼此分隔。

例子:

Input = hello

Output = hel*lo
Run Code Online (Sandbox Code Playgroud)

我的代码:

def pairStar(s):
    if len(s)<=1:
        return s
    if s[0]==s[1]:
        return s[0]+"*"+pairStar(s[1:])

string=input()
print(pairStar(string))

My input: hello

My output: None
Run Code Online (Sandbox Code Playgroud)

请帮忙!输出显示“None”而不是“hel*lo”。

Adi*_*did 5

return如果字符串长度超过 1 并且前 2 个字符不是匹配对,您将错过另一个调用:

def pairStar(s):
    if len(s)<=1:
        return s
    if s[0]==s[1]:
        return s[0]+"*"+pairStar(s[1:])
    return s[0] + pairStar(s[1:])

string=input()
print(pairStar(string))
Run Code Online (Sandbox Code Playgroud)