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.
题目描述:删除 s 中的一些字符,使得它构成字符串列表 d 中的一个字符串,找出能构成的最长字符串。如果有多个相同长度的结果,返回字典序的最小字符串。
class Solution {
public String findLongestWord(String s, List<String> d) {
String longest = "";
for(String dict:d){
int i=0;
for(char c:s.toCharArray()){//字符串转为字符数组;;字符串直接提取字符
if(i<dict.length()&&c == dict.charAt(i)) i++;//若等于dict中某个字符,指针移动一位
if(i==dict.length()||i<=longest.length()){
if(i>longest.length()||dict.compareTo(longest)<0){//两种情况,一是长度小于最长,二是字典序最小 compareTo(longest)<0 说明参数字典序小 =0 正好 >0字典序大
longest = dict;
}
}
}
}
return longest;
}
}