思路:找出s中包含的最长dictionary
外层遍历dictionary,内层双指针
如果遇到一个匹配的dictionary,就先比较长度,再比较字典序
class Solution:
def findLongestWord(self, s: str, dictionary: List[str]) -> str:
res=""
for d in dictionary:
i=j=0
while i<len(d) and j<len(s):
if d[i]==s[j]:
i+=1
j+=1
if i==len(d):
if len(d)>len(res) or (len(d)==len(res) and d<res):
res=d
return res
class Solution {
public String findLongestWord(String s, List<String> dictionary) {
String res="";
for(String d : dictionary){
int i=0,j=0;
while(i<s.length() && j<d.length()){
if(s.charAt(i)==d.charAt(j)){
j++;
}
i++;
}
if(j==d.length()){
if(d.length()>res.length() ||
(d.length()==res.length() && d.compareTo(res)<0)){
res=d;
}
}
}
return res;
}
}
也可以先将dictionary按长度和字典序排好,再遍历双指针
class Solution {
public String findLongestWord(String s, List<String> dictionary) {
Collections.sort(dictionary, (a,b)->{
if (a.length() != b.length()) return b.length() - a.length();
return a.compareTo(b);
});
int n = s.length();
for (String d : dictionary) {
int m = d.length();
int i = 0, j = 0;
while (i < n && j < m) {
if (s.charAt(i) == d.charAt(j)) j++;
i++;
}
if (j == m) return d;
}
return "";
}
}