处理字符串子序列问题,如果使用dfs,那么不就不但是子序列(即删除其中的一部分),还会遍历出其他的顺序,即不按原顺序排列的子字符串。
但如果采用双指针和贪心的方法去匹配,那么得到的序列一定是其的子序列。
compareTo比较函数,直接调用即可 例如 st
class Solution {
public String findLongestWord(String s, List<String> dictionary) {
String res = "";
for (String t : dictionary) {
int i = 0, j = 0;
while (i < t.length() && j < s.length()) {
if (t.charAt(i) == s.charAt(j)) {
++i;
}
++j;
}
if (i == t.length()) {
if (t.length() > res.length() || (t.length() == res.length() && t.compareTo(res) < 0)) {
res = t;
}
}
}
return res;
}
}
r.compareTo,返回结果<0 表示字典序比其小