我们有一个字符串 s
我们有一个数字n
下面是一个函数,它采用字符串,将偶数索引字符连接到前面,将奇数索引字符连接到后面。
例子
s = "Wow Example!"
result = "WwEapeo xml!"
s = "I'm JomoPipi"
result = "ImJm ii' ooPp"
任务:
在将函数应用到字符串 n 次后,返回字符串的结果。
例如,s = “qwertyuio” 和 n = 2:
after 1 iteration s = "qetuowryi"
after 2 iterations s = "qtorieuwy"
return "qtorieuwy"
注意
有很多测试,大字符串,n大于十亿
所以准备好优化。
题目难度:一般
题目来源:String → N iterations → String | Codewars
def jumbled_string(s: str, n: int) -> str:
# you've made it this far, now finish it!
pass
assert jumbled_string("Such Wow!",1) == "Sc o!uhWw"
assert jumbled_string("better example",2) == "bexltept merae"
assert jumbled_string("qwertyuio",2) == "qtorieuwy"
assert jumbled_string("Greetings",8) == "Gtsegenri"
joyoko
(徐子宇)
2022 年7 月 22 日 02:46
2
def jumbled_string(s: str, n: int) -> str:
# you've made it this far, now finish it!
start_num = 0
while start_num < n:
single_index_str = []
pair_index_str = []
for i in range(len(s)):
if i % 2 == 0:
pair_index_str.append(s[i])
else:
single_index_str.append(s[i])
s = "".join((pair_index_str+single_index_str))
start_num += 1
return s
assert jumbled_string("Such Wow!", 1) == "Sc o!uhWw"
assert jumbled_string("better example", 2) == "bexltept merae"
assert jumbled_string("qwertyuio", 2) == "qtorieuwy"
assert jumbled_string("Greetings", 8) == "Gtsegenri"
时间复杂度不够哦,还有优化的方案,循环多了之后计算量有点大
def jumbled_string(s: str, n: int):
# you've made it this far, now finish it!
for i in range(n):
s_l = [item for index, item in enumerate(s) if index % 2 == 0]
s_r = [item for index, item in enumerate(s) if index % 2 != 0]
s = s_l + s_r
return "".join(s)
assert jumbled_string("Such Wow!",1) == "Sc o!uhWw"
assert jumbled_string("better example",2) == "bexltept merae"
assert jumbled_string("qwertyuio",2) == "qtorieuwy"
assert jumbled_string("Greetings",8) == "Gtsegenri"
def jumbled_string(s, n):
count = 0
s_list=list(s)
old_s=s_list
while count < n:
s_list=s_list[::2]+s_list[1::2]
#找到交换多少次后还原的次数,然后重新计算需要交换的次数
if s_list==old_s:
n = n % (count+1)
count = 0
s=old_s
continue
count += 1
return ''.join(s_list)
qunzi
(群子)
2023 年3 月 15 日 07:04
14
def jumbled_string(s: str, n: int) -> str:
while n!=0:
res=s[0::2]+s[1::2]
n=n-1
if n!=0:
return jumbled_string(res,n)
else:
return res
def changestr(tar, num):
for i in range(num):
tar = tar[::2] + tar[1::2]
return tar
lekaixin
(ALe阿乐)
2023 年12 月 3 日 04:07
18
ef jumbled_string(s: str, n: int) -> str:
t=0
while t<n:
s=s[::2]+s[1::2]
t+=1
return s
assert jumbled_string("Such Wow!",1) == "Sc o!uhWw"
assert jumbled_string("better example",2) == "bexltept merae"
assert jumbled_string("qwertyuio",2) == "qtorieuwy"
assert jumbled_string("Greetings",8) == "Gtsegenri"