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.
Example 1:
Input: s = "abpcplea", d = ["ale","apple","monkey","plea"] Output: "apple"
Example 2:
Input: s = "abpcplea", d = ["a","b","c"] Output: "a"
Note:
- All the strings in the input will only contain lower-case letters.
- The size of the dictionary won't exceed 1,000.
- The length of all the strings in the input won't exceed 1,000.
题目含义: 给一个string s和一个string字典d,找字典中的某个string,寻找s的子串(满足可以通过删除s中某些元素后得到该string),寻找满足条件的字符串中最长的一个,如果有多个长度相等的就返回字典序中最小的那个,如果一个都没有满足条件的string,就返回一个空字符串~
1 public String findLongestWord(String s, List<String> d) { 2 Collections.sort(d, (a, b) -> a.length() != b.length() ? -Integer.compare(a.length(), b.length()) : a.compareTo(b)); 3 char[] chars = s.toCharArray(); 4 for (String dict : d) { 5 int i = 0; 6 for (char c : chars) { 7 if (i < dict.length() && c == dict.charAt(i)) i++; 8 } 9 if (i == dict.length()) { 10 return dict; 11 } 12 } 13 return ""; 14 }