雙指針/貪心
524. 通過刪除字母匹配到字典里最長單詞
處理字符串子序列問題,如果使用dfs,那么不就不但是子序列(即刪除其中的一部分),還會(huì)遍歷出其他的順序,即不按原順序排列的子字符串。
但如果采用雙指針和貪心的方法去匹配,那么得到的序列一定是其的子序列。
compareTo比較函數(shù),直接調(diào)用即可 例如 str.compareTo,返回結(jié)果<0??表示字典序比其小
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;
? ? }
}