闲来有空,Leetcode面试题拿来练练手。题目如下:
这道题比较冷门,题目看起来比较简单易懂,其实做起来思路也比较清洗:
1、先将可能单词中所含的单词用字典存储起来
2、对单词及其可能含有的词的字典进行回溯法(核心,其实也就是对字典进行回溯),找出相加起来等于该单词的Key
代码如下(代码可直接复制使用):
str_list= ["cat","banana","dog","nana","walk","walker","dogwalker"]
dict_2={}
#一、对单词及其可能含有的词的字典进行回溯法,
def syr_1(dict_2,num,key,str_number = ''):
new_list=[]
for i in num:
num_copy=num.copy()
num_copy.remove(i)
str_number+=i
new_list.append(i)
number_1=''
if str_number==key:
new_list_3.append(key)
break
syr_1(dict_2,num_copy,key,number_1)
#二、先将可能单词中所含的单词用字典存储起来
for str_1 in str_list:
str_list_copy=str_list.copy()
str_list_copy.remove(str_1)
for str_2 in str_list_copy:
if str_2 in str_1:
dict_2.setdefault(str_1,[])
dict_2[str_1].append(str_2)
#输出key
for key,value_list in dict_2.items():
str_number=0
new_list_3=[]
syr_1(dict_2,value_list,key)
if new_list_3:
print(key)
输出结果如下,为了使效果更好,本人加上了更多的单词进行测试