194题 Find Words

本文介绍了一种算法,该算法接收一个字符串和一个字典作为输入,并返回字典中所有作为输入字符串子序列的单词。文章详细解释了如何遍历字符串并与字典中的每个单词进行比较的过程。

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 ;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值