ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LintCode] 194. Find Words

2022-06-12 08:32:48  阅读:191  来源: 互联网

标签:word 194 LintCode 单词 length dict str return Find


Given a string str and a dictionary dict, you need to find out which words in the dictionary are subsequences of the string and return those words.The order of the words returned should be the same as the order in the dictionary.

  1. |str|<=1000
  2. the sum of all words length in dictionary<=1000

(All characters are in lowercase)

Example 1:

Input:
str="bcogtadsjofisdhklasdj"
dict=["book","code","tag"]
Output:
["book"]
Explanation:Only book is a subsequence of str

Example 2:

Input:
str="nmownhiterer"
dict=["nowhere","monitor","moniter"]
Output:
["nowhere","moniter"]

|str|<=100000

寻找单词。

给定一个字符串str,和一个字典dict,你需要找出字典里的哪些单词是字符串的子序列,返回这些单词。返回单词的顺序应与词典中的顺序相同。

这道题类似 LeetCode 392题 找子序列,这里我也给出一个类似的做法。对于 dict 里的每一个单词,我们拿出来跟 str 去比较,看这个单词是否是 str 的子序列,如果是就加入结果集。

时间O(m*n) - n是单词个数,m是单词的平均长度

空间O(n) - output list size

Java实现

 1 public class Solution {
 2     public List<String> findWords(String str, List<String> dict) {
 3         List<String> res = new ArrayList<>();
 4         for (String word : dict) {
 5             if (helper(word, str)) {
 6                 res.add(word);
 7             }
 8         }
 9         return res;
10     }
11 
12     private boolean helper(String word, String str) {
13         // corner case
14         if (word == null || word.length() == 0) {
15             return true;
16         }
17 
18         // normal case
19         int i = 0;
20         int j = 0;
21         while (i < word.length() && j < str.length()) {
22             if (word.charAt(i) == str.charAt(j)) {
23                 i++;
24             }
25             j++;
26         }
27         return i == word.length();
28     }
29 }

 

相关题目

[LintCode] 194. Find Words

[LeetCode] 392. Is Subsequence

LeetCode 题目总结

标签:word,194,LintCode,单词,length,dict,str,return,Find
来源: https://www.cnblogs.com/cnoodle/p/16367365.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有