问题:app
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.ide
Example 1:spa
Input: s = "abpcplea", d = ["ale","apple","monkey","plea"] Output: "apple"
Example 2:.net
Input: s = "abpcplea", d = ["a","b","c"] Output: "a"
Note:orm
解决:排序
① 这道题给了咱们一个字符串,和一个字典,让咱们找到字典中最长的一个单词,这个单词能够经过给定单词经过删除某些字符获得。因为只能删除某些字符,并不能从新排序,因此咱们不能经过统计字符出现个数的方法来判断是否能获得该单词,而是只能老老实实的按顺序遍历每个字符。字符串
咱们能够给字典排序,经过重写comparator来实现按长度由大到小来排,若是长度相等的就按字母顺序来排。而后咱们开始遍历每个单词,用一个变量i来记录单词中的某个字母的位置,咱们遍历给定字符串,若是遍历到单词中的某个字母来,i自增1,若是没有,就继续往下遍历。这样若是最后i和单词长度相等,说明单词中的全部字母都按顺序出如今了字符串s中,因为字典中的单词已经按要求排过序了,因此第一个经过验证的单词必定是正确答案,咱们直接返回当前单词便可。get
class Solution {//32ms
public String findLongestWord(String s, List<String> d) {
if (d == null || d.size() == 0) return "";
String[] dirs = new String[d.size()];
for(int i = 0;i < d.size();i ++){
dirs[i] = d.get(i);
}
Arrays.sort(dirs, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() == o2.length()){//按照字典序排序
return o1.compareTo(o2);
}
return o2.length() - o1.length();//按照字符串长度由大到小排序
}
});
for (String str : dirs){
int i = 0;
for (char c : s.toCharArray()){
if (i < str.length() && c == str.charAt(i)) i ++;
}
if (i == str.length()) return str;
}
return "";
}
}input
② 不须要排序的方法,咱们遍历字典中的单词,而后仍是跟上面的方法同样来验证当前单词是否能由字符串s经过删除字符来获得,若是能获得,并且单词长度大于等于结果res的长度,咱们再看是否须要更新结果res,有两种状况是必需要更新结果res的,一个是当前单词长度大于结果res的长度,另外一种是当前单词长度和res相同,可是字母顺序小于结果res,这两种状况下更新结果res便可。string
class Solution { //44ms public String findLongestWord(String s, List<String> d) { String res = ""; for (String str : d){ int i = 0; for(char c : s.toCharArray()){ if (i < str.length() && c == str.charAt(i)) i ++; } if (i == str.length() && str.length() >= res.length()){ if (str.length() > res.length() || str.compareTo(res) < 0){ res = str; } } } return res; } }