Leetcode: https://leetcode.cn/problemset/?page=1&search=%E6%9C%80%E9%95%BF%E5%AD%97%E7%AC%A6%E4%B8%B2
给定一组单词words
,编写一个程序,找出其中的最长单词,且该单词由这组单词中的其他单词组合而成。若有多个长度相同的结果,返回其中字典序最小的一项,若没有符合要求的单词则返回空字符串。
示例:
输入: ["cat","banana","dog","nana","walk","walker","dogwalker"] 输出: "dogwalker" 解释: "dogwalker"可由"dog"和"walker"组成。
提示:
0 <= len(words) <= 200
1 <= len(words[i]) <= 100
Java:
class Solution { public String longestWord(String[] words) { Arrays.sort(words,(o1,o2)->{ if(o1.length() == o2.length()) return o1.compareTo(o2); else{ return Integer.compare(o2.length(),o1.length()); } }); Set<String> set = new HashSet<>(Arrays.asList(words)); for(String word : words){ set.remove(word); if(find(set,word)) return word; } return ""; } public boolean find(Set<String> set, String word){ if(word.length() == 0) return true; for(int i = 0; i < word.length(); i++){ if(set.contains(word.substring(0,i+1)) && find(set,word.substring(i+1))) return true; } return false; } }
Python:
class Solution: def longestWord(self, words: List[str]) -> str: words.sort(key = lambda x: (-len(x), x)) def dfs(w, words): if not w: return True for i, nxt in enumerate(words): if nxt == w[:len(nxt)]: if dfs(w[len(nxt):], words): return True return False for i, word in enumerate(words): if dfs(word, words[i+1:]): return word return ''
思想:
1.先按要求对数组按字符串长度、字典序排序,因为要找符合条件的最长字符串,从最长的开始判断,满足就可以结束了;
2.遍历字符串,进行判断:在词典中map去除当前字符串,遍历当前字符串,看每个截断点前半部分是否在词典库中,在说明当前字符串包含其它字符串,再后将截断点后半部分作为新字符串递归判断是否仍是满足条件的子串串,知道字符串长度为0,说明整个字符串都是由其它字符串组成的;