简体   繁体   English

用递归将字符串字符加倍

[英]Doubling string characters with recursion

假设我有字符串“my name is”,我如何递归地返回字符串“mmyy nnammee iiss”?

you could do something like你可以做类似的事情

def double(s):
  out = ''
  for letter in s:
    out=out+s+s
  return out

this has这有

INPUT:print(double("hello"))
OUTPUT:hheelllloo

The following is simple enough.下面就够简单了。 Double the first letter, and recursively call for the rest.将第一个字母加倍,然后递归调用其余的字母。 Base case: empty string:基本情况:空字符串:

def double(s):
    if not s:
        return s
    return 2 * s[0] + double(s[1:])

double("my name is")
# 'mmyy  nnaammee  iiss'

Note that the repeated slicing of the recursive approach and the repeated string concatenation of the other answer make both solutions quadratic in time complexity.请注意,递归方法的重复切片和另一个答案的重复字符串连接使两个解决方案的时间复杂度都是二次的。 Algorithmically sounder (linear) would be str.join ing a linearly built list or a generator expression:算法上更健全(线性)将是str.join线性构建的列表或生成器表达式:

def double(s):
    return "".join(2*c for c in s)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM