lintcode 寻找单词
题目
给定一个字符串str,和一个字典dict,你需要找出字典里的哪些单词是字符串的子序列,返回这些单词。
样例
输入:
str=“bcogtadsjofisdhklasdj”
dict=[“book”,“code”,“tag”]
输出:
[“book”]
解释:只有book是str的子序列
分析
暴力法,依次判断,后续再想想优化。
代码
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) {
List<String> list = new ArrayList<>();
for (String word : dict) {
if (isSubsequence(word, str)) {
list.add(word);
}
}
return ls;
}
private boolean isSubsequence(String w, String str) {
int p = 0;
for (int i = 0; i < w.length(); i++) {
while (p < str.length() && str.charAt(p) != w.charAt(i)) {
p++;
}
// 如果没找到,返回false
if (p == str.length()) {
return false;
}
// 找到字符后,找下一个字符
p++;
}
return true;
}
}