码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] 194. Find Words

时间:2020-03-18 10:05:00      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:new   char   nbsp   ble   break   item   cti   start   you   

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

标签:new   char   nbsp   ble   break   item   cti   start   you   

原文地址:https://www.cnblogs.com/xuanlu/p/12515161.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!