Find Words
Description
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.
|str|<=1000
the sum of all words length in dictionary<=1000
(All characters are in lowercase)
Example
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”]
public class Solution {
/**
* @param str: the string
* @param dict: the dictionary
* @return: return words which are subsequences of the string
*/
public List<String> findWords(String str, List<String> dict) {
// write your code here.
int n = dict.size() ;
int[] index = new int[n] ;
for(int i = 0 ; i < str.length() ; i++){
for(int j = 0 ; j < n ; j++){
if(index[j] == -1){
continue ;
}else if (dict.get(j).charAt(index[j]) == str.charAt(i)){
index[j]++ ;
}
if(index[j] == dict.get(j).length()){
index[j] = -1 ;
}
}
}
List<String> res = new ArrayList<>();
for(int i = 0 ; i < n ; i++){
if(index[i] == -1){
res.add(dict.get(i)) ;
}
}
return res ;
}
}
本文介绍了一种算法,该算法接收一个字符串和一个字典作为输入,并返回字典中所有作为输入字符串子序列的单词。文章详细解释了如何遍历字符串并与字典中的每个单词进行比较的过程。
5万+

被折叠的 条评论
为什么被折叠?



