【字符串】面试题 17.15. 最长单词

题目:

 

 

解答:

解题思路:

(1)使用哈希集合存储列表中的每一个单词,接着遍历列表的中的每个单词判断其是否由其他单词组合而成;

(2)递归查找时,因为不能由其自身组成,因此每次从哈希集合中删除其自身;

(3)递归分割查找每一种可能,当一种分割到空串时,返回true,所有的情况遍历完毕,返回false;

 1 class Solution {
 2 public:
 3     string longestWord(vector<string>& words) 
 4     {
 5         // 通过interator来复制vector到unordered_set
 6         unordered_set<string> allwords(words.begin(),words.end());
 7         string ans;
 8 
 9         for(auto word:allwords)
10         {
11             // 通过auto复制集合
12             auto temp=allwords;
13             // erase()传入元素可删除集合中的元素
14             temp.erase(word);
15 
16             if(isCombinated(word,temp))
17             {
18                 //查找word是否是其他元素組合
19                 if(word.size()>ans.size()) 
20                 {
21                     ans=word;
22                 }
23                 if(word.size()==ans.size()) 
24                 {
25                     // Min傳入string,同樣長度情況下。min返回字典序小的那個string,實現返回通長度下字典序較小元素
26                     ans=min(word,ans);
27                 }
28             }
29         }
30         return ans;
31     }
32 
33     bool isCombinated(string word,unordered_set<string>& words)
34     {
35         if(word.size()==0) 
36         {
37             return true;
38         }
39         for(int i=1;i<=word.size();i++)
40         {
41             // substr记录首位不记录末尾终点,所以i取等号为迭代末尾
42             if(words.count(word.substr(0,i))&&isCombinated(word.substr(i), words)) 
43             {
44                 return true;//words.count()查看元素是否在集合内,如果不在返回0
45             }
46         }
47         return false;
48     }
49 };

 

posted @ 2020-05-04 15:13  梦醒潇湘  阅读(227)  评论(0)    收藏  举报