### 题目

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","monkey", "apple", "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.

### 怎么判定字符串能否缩减？

0 2 456
| | |||
abpcplea

01234
|||||
apple


### 可以先排序

1. 先按照字母排序（升序）
2. 再按照字符串长度排序（降序）

#### 代码

class Solution {
public String findLongestWord(String s, List<String> d) {
Collections.sort(d);
Collections.sort(d, (String a, String b) -> b.length() - a.length());
for (String w : d) {
if (canReductTo(s, w)) return w;
}
return "";
}

private boolean canReductTo(String from, String to) {
int pf = 0, pt = 0;
int lf = from.length(), lt = to.length();
while (pt < lt) {
char ct = to.charAt(pt);
while (pf < lf && from.charAt(pf) != ct) pf++;
if (pf == lf) return false;
pf++; pt++;
}
return true;
}
}


### 也可以不排序

#### 代码

class Solution {
public String findLongestWord(String s, List<String> d) {
int maxLen = 0;
String maxString = "~"; // in ascii table "~" is larger than "a"
for (String w : d) {
if ((w.length() > maxLen || (w.length() == maxLen && w.compareTo(maxString) < 0)) && canReductTo(s, w)) {
maxLen = w.length();
maxString = w;
}
}
return (maxString.equals("~"))? "" : maxString;
}

private boolean canReductTo(String from, String to) {
int pf = 0, pt = 0;
int lf = from.length(), lt = to.length();
while (pt < lt) {
char ct = to.charAt(pt);
while (pf < lf && from.charAt(pf) != ct) pf++;
if (pf == lf) return false;
pf++; pt++;
}
return true;
}
}