简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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