字典树:Leetcode 720:词典中最长的单词

r囧r小猫 2023-10-06 08:43 58阅读 0赞

字典树:Leetcode 720:词典中最长的单词

问题:

在这里插入图片描述
在这里插入图片描述

思路:

1.排序+哈希表

考虑将排序后的字符串散列到unordered_set中

对于排序后的输入,依次寻找字符串的子串是否在unordered_set中,首先子串中只包含第一个字符,随后子串增加第二个字符,以此类推,直至子串包含倒数第二个字符。若这些子串全都存在,则该字符串由词典中的单词组成,若此时该字符串长度也为满足条件的单词中最大的,则可以输出答案了,因此在排序中字符串长度长的应排在前面

由于题中要找出最长的单词,应改变排序策略,若两字符串长度相同,则应满足按字典序排列,若长度不同,长度更长的需排在前面,应对sort()函数提供排序函数,使得满足上述排序策略

2.前缀树(字典树)

前缀树文章在此
直接建立前缀树数据结构
依次将输入中的字符串插入到前缀树中
最长单词的每个字符在前缀树中对应的节点都能表示一个字符串
建立好前缀树后,在前缀树中依次查找输入中的字符串,若字符串中的每个字符都在前缀树中且都为完整字符串,则查找成功
在成功查找的字符串中选择最长串输出,若长度相同,选择字典序小的

代码:

1.排序+哈希表
  1. class Solution {
  2. public:
  3. static bool cmp( string &A,string &B )
  4. {
  5. return A.size()!=B.size()? A.size()>B.size() : A<B;
  6. }
  7. string longestWord(vector<string>& words) {
  8. unordered_set<string> table;
  9. sort( words.begin(),words.end(),cmp );
  10. for( string A:words )
  11. table.insert(A);
  12. int i;
  13. for( string A:words )
  14. {
  15. for( i=1;i<A.size();i++ )
  16. {
  17. if( table.find( A.substr( 0,i ) )==table.end() )
  18. break;
  19. }
  20. if( i==A.size() )
  21. return A;
  22. }
  23. return "";
  24. }
  25. };
2.前缀树
  1. class Solution {
  2. public:
  3. struct TrieNode
  4. {
  5. TrieNode* next[26];
  6. bool isStr;
  7. };
  8. void insert( TrieNode* root,string s )
  9. {
  10. TrieNode* location=root;
  11. int i=0;
  12. while( s[i] )
  13. {
  14. if( location->next[ s[i]-'a' ]==NULL )
  15. {
  16. TrieNode* newNode=new TrieNode();
  17. newNode->isStr=false;
  18. memset( newNode->next,NULL,sizeof(newNode->next) );
  19. location->next[ s[i]-'a' ]=newNode;
  20. }
  21. location=location->next[ s[i]-'a' ];
  22. i++;
  23. }
  24. location->isStr=true;
  25. }
  26. bool search( TrieNode* root,string s )
  27. {
  28. TrieNode* location=root;
  29. for(const auto& w:s){
  30. if(location->next[w-'a']==nullptr||location->next[w-'a']->isStr==false)return false;
  31. location=location->next[w-'a'];
  32. }
  33. return true;
  34. }
  35. string longestWord(vector<string>& words) {
  36. TrieNode* root=new TrieNode();
  37. memset( root->next,NULL,sizeof(root->next) );
  38. for( string temp:words )
  39. insert( root,temp );
  40. string ans="";
  41. for( string temp:words )
  42. {
  43. if( search( root,temp ) )
  44. {
  45. if( temp.size()>ans.size() )
  46. ans=temp;
  47. else if( temp.size()==ans.size() )
  48. {
  49. if( temp<ans )
  50. ans=temp;
  51. }
  52. }
  53. }
  54. return ans;
  55. }
  56. };

发表评论

表情:
评论列表 (有 0 条评论,58人围观)

还没有评论,来说两句吧...

相关阅读