[LeetCode]524.通过删除字母匹配到字典里最长单词.

22
2020/06

# [LeetCode]524.通过删除字母匹配到字典里最长单词.

## 题目

s = "abpcplea", d = ["ale","apple","monkey","plea"]

"apple"

s = "abpcplea", d = ["a","b","c"]

"a"

Related Topics 排序 双指针
https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting/

## 代码

class Solution {
public String findLongestWord(String s, List<String> d) {
String longestWord = "";//ans 初始化
for (String target : d) {//遍历所有单词
int l1 = longestWord.length(), l2 = target.length();//最长串 和 l2// 目标单词的长度
//不满足的条件
if (l1 > l2 || (l1 == l2 && longestWord.compareTo(target) < 0)) {//新单词和单词比较 判断符不符合：单词最长 单词长度相同字典序最小
continue;//换单词
}
//满足条件 求是否存在子串 并返回最长
if (isSubStr(s, target)) {
longestWord = target;
}
}
return longestWord;
}

/**
* 字串判断
*
* @param s      长串
* @param target 短串
* @return
*/
private boolean isSubStr(String s, String target) {
int i = 0, j = 0;
while (i < s.length() && j < target.length()) {
if (s.charAt(i++) == target.charAt(j)) {
j++;
}
}
return j == target.length();
}
}

百度已收录

Last modification：June 22nd, 2020 at 08:29 pm