描述
给定一个字符串 s 和一个字符串数组 dic ,在字符串 s 的任意位置添加任意多个空格后得到的字符串集合是给定字符串数组 dic 的子集(即拆分后的字符串集合中的所有字符串都在 dic 数组中),你可以以任意顺序 返回所有这些可能的拆分方案。
数据范围:字符串长度满足 1 \le n \le 20 \1≤n≤20 ,数组长度满足 1 \le n \le 10 \1≤n≤10 ,数组中字符串长度满足 1 \le n \le 20 \1≤n≤20
输入:"nowcoder",["now","coder","no","wcoder"]
返回值:["no wcoder","now coder"]
'''
描述
给定一个字符串 s 和一个字符串数组 dic ,在字符串 s 的任意位置添加任意多个空格后得到的字符串集合是给定字符串数组 dic 的子集(即拆分后的字符串集合中的所有字符串都在 dic 数组中),你可以以任意顺序 返回所有这些可能的拆分方案。
数据范围:字符串长度满足 1 \le n \le 20 \1≤n≤20 ,数组长度满足 1 \le n \le 10 \1≤n≤10 ,数组中字符串长度满足 1 \le n \le 20 \1≤n≤20
'''
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param s string字符串
# @param dic string字符串一维数组
# @return string字符串一维数组
#
# class Solution:
# def wordDiv(self , s: str, dic: List[str]) -> List[str]:
# # write code here
s, dic = "nowcoder",["now","coder","no","wcoder"] # 测试用例
class Solution:
def wordDiv(self, s: str, dic):
# write code here
sentence_all = []
while dic:
sentence = []
left = 0
right = 0
while left < len(s):
words = set(dic).intersection(set([s[left:right]])) # 找到交集
if words:
sentence.append(list(words)[0])
left = right
right += 1
else:
right += 1
sentence_all.append(' '.join(sentence))
dic = list(set(dic) - set(sentence))
return sentence_all
solu = Solution()
solu.wordDiv(s, dic)
![](https://i-blog.csdnimg.cn/blog_migrate/2e73ecfc6995a18e33a7ef6fa19fd13c.png)
测试用例没完全通过
想尝试使用递归但是一直提示
![](https://i-blog.csdnimg.cn/blog_migrate/5afe35293824405e3685019ad2f4324a.png)
有什么好的办法么
s, dic = "nowcoder",["now","coder","no","wcoder"]
class Solution:
def __init__(self):
self.sentence_all = []
def wordDiv(self, s: str, dic):
# write code here
sentence = []
left = 0
right = 0
while left < len(s):
words = set(dic).intersection(set([s[left:right]]))
if words:
sentence.append(list(words)[0])
left = right
right += 1
else:
right += 1
self.sentence_all.append(' '.join(sentence))
dic = list(set(dic) - set(sentence))
if dic:
self.wordDiv(s, dic)
else:
return self.sentence_all