public class Solution {
public string FindLongestWord(string s, IList<string> d) {
string longest = "";
foreach (var dictWord in d)
{
int i = ;
foreach (var c in s)
{
if (i < dictWord.Length && c == dictWord[i])
{
i++;
}
} if (i == dictWord.Length && dictWord.Length >= longest.Length)
{
if (dictWord.Length > longest.Length || dictWord.CompareTo(longest) < )
{
longest = dictWord;
}
}
}
return longest;
}
}
https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/#/description
补充一个python的实现:
class Solution:
def findLongestWord(self, s: str, d: 'List[str]') -> str:
maxlen = 0
longestword = ''
for sd in d:
curlen = 0
i=0
j=0
while i<len(s) and j<len(sd):
if s[i]==sd[j]:
curlen += 1
if curlen == len(sd):
if curlen > maxlen or (curlen == maxlen and sd<longestword):
maxlen = curlen
longestword = sd break
else:
i+=1
j+=1
else:
i+=1
return longestword
再补充一个java实现:
class Solution {
public String findLongestWord(String s, List<String> d) {
String longestWord = "";
for (String target : d) {
int l1 = longestWord.length(), l2 = target.length();
if (l1 > l2 || (l1 == l2 && longestWord.compareTo(target) < )) {
continue;
}
if (isSubstr(s, target)) {
longestWord = target;
}
}
return longestWord;
} private boolean isSubstr(String s, String target) {
int i = , j = ;
while (i < s.length() && j < target.length()) {
if (s.charAt(i) == target.charAt(j)) {
j++;
}
i++;
}
return j == target.length();
}
}