[LintCode] 194. Find Words


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,你需要找出字典里的哪些单词是字符串的子序列,返回这些单词。返回单词的顺序应与词典中的顺序相同。

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

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

空间O(n) - output list size

Java实现

 1 public class Solution {
 2     public List findWords(String str, List dict) {
 3         List 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 }

相关题目