[LintCode] 194. Find Words

Posted xuanlu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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.

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"]

Solution 1:
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.
        List<String> res = new ArrayList<>();
        for (String item: dict) {
            int sItem = 0;
            int sStart = 0;
            while (sItem < item.length() && sStart < str.length()) {
                if (item.charAt(sItem) == str.charAt(sStart)) {
                    sItem += 1;
                }
                if (sItem == item.length()) {
                    res.add(item);
                    break;
                }
                sStart += 1;
            }
        }
        return res;
    }
}

 

 

 

以上是关于[LintCode] 194. Find Words的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-medium-Find Peak Element

lintcode 中等题:word search 单词搜索

lintcode-medium-Find the Missing Number

lintcode-easy-Length of Last Word

LintCode-编辑距离

[LintCode] Add and Search Word 添加和查找单词