leetcode
按照子產品刷題,點選進入使用的刷題目錄
雙指針
7.通過删除字母比對到字典裡最長單詞
題目描述:
通過删除字母比對到字典裡最長單詞
解題思路:
1.首先寫一個判斷s是否為d子串的函數,若遇到不相同的字元,則字元串s向右移動一個字元,否則,字元串s和d均向右移動一個字元,若字元串d移動到末尾,則說明d是s的子串。
2.接着在尋找最長單詞的函數中,設定字元串longestWord為空,周遊dictionary中的單詞,若長度大于longestWord的長度或者長度相等且字典順序較小,則判斷其是否為子串,若是,則更新longestWord的值。周遊結束後傳回longestWord。
代碼:
class Solution {
public String findLongestWord(String s, List<String> dictionary) {
String longestWord="";
for(String d:dictionary){
int l1=longestWord.length(),l2=d.length();
if(l1>l2||l1==l2&&longestWord.compareTo(d)<0){
continue;
}
if(isSubstr(s,d)){
longestWord=d;
}
}
return longestWord;
}
private boolean isSubstr(String s,String d){
int i=0,j=0;
while(i<s.length()&&j<d.length()){
if(s.charAt(i)==d.charAt(j)){
j++;
}
i++;
}
return j==d.length();
}
}
注:
ArrayList類
LinkedList類
compareTo() 方法
charAt() 方法