# Python递归通过滑动窗口拆分字符串

##### 问题描述投票：-2回答：1

``````s = "iamfoobar"
k = 4  # the max number of the items on a list after the split
``````

`s`可以分为以下组合

``````[
["i", "a", "m", "foobar"],
["ia", "m", "f", "oobar"],
["iam", "f", "o", "obar"]
# etc
]
``````

``````def sliding(s, k):
if len(s) < k:
return []
else:
for i in range(0, k):
return [s[i:i+1]] + sliding(s[i+1:len(s) - i], k)

print(sliding("iamfoobar", 4))

``````

``````['i', 'a', 'm', 'f', 'o', 'o']
``````
python python-3.x
##### 1个回答
0

``````def sliding(s, k):
# If there is not enough values of k is below 0
# there is no combination possible
if len(s) < k or k < 1:
return []

# If k is one, we return a list containing all the combinations,
# which is a single list containing the string
if k == 1:
return [[s]]

results = []
# Iterate through all the possible values for the first value
for i in range(1, len(s) - k + 2):
first_value = s[:i]
# Append the result of the sub call to the first values
for sub_result in sliding(s[i:], k - 1):
results.append([first_value] + sub_result)

return results

print(sliding("iamfoobar", 4))
``````