524. 通過刪除字母匹配到字典里最長單詞
給你一個字符串 s 和一個字符串數組 dictionary 作為字典,找出并返回字典中最長的字符串,該字符串可以通過刪除 s 中的某些字符得到。
如果答案不止一個,返回長度最長且字典序最小的字符串。如果答案不存在,則返回空字符串。
示例 1:輸入:s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
輸出:"apple"
示例 2:輸入:s = "abpcplea", dictionary = ["a","b","c"]
輸出:"a"
提示:
- 1 <= s.length <= 1000
- 1 <= dictionary.length <= 1000
- 1 <= dictionary[i].length <= 1000
- s 和 dictionary[i] 僅由小寫英文字母組成
解題思路
使用雙指針可以很直接判斷字典里面的字符串,是否屬于s的一個子序列。遍歷字典中,所有的字符串,找出長度最長且字典序最小,屬于s的子序列的字符串
代碼
class Solution {public String findLongestWord(String s, List<String> dictionary) {int res=0;String ret="";for(String k:dictionary){if(k.length()>s.length()||!longest(s,k)) continue;if(k.length()>res||ret.length()==0||k.length()==res&&ret.compareTo(k)>0){res=k.length();ret=k;}}return ret;}public boolean longest(String a,String b){int l=0,r=0;while(l<a.length()&&r<b.length()){if(a.charAt(l)==b.charAt(r))r++;l++;}return r==b.length();}
}