初级农民-请到新手上路获取积分
- 积分
- 6
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2018-1-31
- 最后登录
- 1970-1-1
|
题4。只是实现了主要算法。
- static class TrieNode {
- public TrieNode[] nodes = new TrieNode[26];
- public String word;
- }
- public static List<String> findWordInStream(char[] chs, String[] words) {
- TrieNode root = new TrieNode();
- for (String word : words) {
- TrieNode curr = root;
- for (char ch : word.toCharArray()) {
- if (curr.nodes[ch - 'a'] == null) {
- curr.nodes[ch - 'a'] = new TrieNode();
- }
- curr = curr.nodes[ch - 'a'];
- }
- curr.word = word;
- }
- List<TrieNode> nodeList = new ArrayList<>();
- Set<String> ansSet = new HashSet<>();
- for (char ch : chs) {
- if (root.nodes[ch - 'a'] != null) {
- TrieNode curr = root;
- nodeList.add(curr);
- }
- List<TrieNode> tmpNodeList = new ArrayList<>();
- for (TrieNode node : nodeList) {
- if (node.nodes[ch - 'a'] != null) {
- node = node.nodes[ch - 'a'];
- if (node.word != null) {
- ansSet.add(node.word);
- }
- tmpNodeList.add(node);
- }
- }
- nodeList = tmpNodeList;
- }
- List<String> ans = new ArrayList<>();
- ansSet.forEach(p -> ans.add(p));
- return ans;
- }
复制代码 |
|