假设我们有两个字符串s,t和另一个正数n,我们必须找到返回序列A的第n个项,其中-
A [0] = s
A [1] = t
当n为偶数时,A [n] = A [n-1] + A [n-2],否则A [n] = A [n-2] + A [n-1]。
例如,如果s =“ a”和t =“ b”,则序列A将为-[“ a”,“ b”,“ ba”(“ a” +“ b”),“ bba”( “ b” +“ ba”),“ bbaba”(“ bba” +“ ba”)]
因此,如果输入类似于s =“ pk”,t =“ r”,n = 4,则输出为“ rrpkrpk”
为了解决这个问题,我们将遵循以下步骤-
如果n等于0,则
返回s
否则,当n等于1时,则
返回t
a:= s,b:= t
对于2到n范围内的i
c:=串联b
c:= b连接a
如果我的mod 2等于0,那么
除此以外,
a:= b
b:= c
返回c
让我们看下面的实现以更好地理解-
class Solution: def solve(self, s, t, n): if n == 0: return s elif n == 1: return t a = s b = t for i in range(2, n+1): if i%2 == 0: c = b + a else: c = a + b a = b b = c return c ob = Solution()print(ob.solve("pk", "r", 4))
"pk", "r", 4
输出结果
rrpkrpk