中级农民
- 积分
- 138
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-9-7
- 最后登录
- 1970-1-1
|
这个问题很有意思:就是问字典中最长的单词长度,使得它是给定的string s的substring (instead of subsequence)。这样我想应该用BFS在字典Trie中做level order traversal,同时更新Trie node所代表的char在s中的index:从Trie root开始,定义index set={-1, 0,...,Ls-2} (Ls=s.length()),对于每个index, 在Trie的下一层看s[index+1]所代表的char在不在Trie中:root->next[s[index+1]-'a']==NULL?若在Trie中就可以加入下一层继续搜索。注意到在Trie同一层的nodes所对应的index set是disjoint,所以时间复杂度实际为O(Ls*min(Ls, Ld)) ,其中Ld=longest word length in dict (i.e., max depth of Trie).
(后来我想到原来的subsequence问题也许也应该用BFS比DFS更清楚一些)- int longestSubstr(string& s, const vector<string>& dict) {
- int ls = s.length(), maxlen = 0, count = -1; Node* node = NULL;
- vector<int> indices; for (int i = 0; i < ls; ++i) indices.push_back(i - 1);
- unordered_map<Node*, vector<int>> idx = { { createTrie(dict, ls), indices } }, next_idx;
- while (!idx.empty()) { // Trie BFS level order traversal to update maxlen
- count++;
- for (auto& p : idx) // O(ls) for double loop since index sets are disjoint
- for (int i : p.second)
- if (i + 1 < ls && (node = p.first->next[s[i + 1] - 'a']))
- { next_idx[node].push_back(i + 1); if (node->isWord) maxlen = max(maxlen, count); }
- idx.clear(); swap(idx, next_idx);
- }
- return maxlen;
- }
复制代码 |
|