public class Solution { public string FindLongestWord(string s, IListd) { string longest = ""; foreach (var dictWord in d) { int i = 0; 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) < 0) { longest = dictWord; } } } return longest; }}
补充一个python的实现:
1 class Solution: 2 def findLongestWord(self, s: str, d: 'List[str]') -> str: 3 maxlen = 0 4 longestword = '' 5 for sd in d: 6 curlen = 0 7 i=0 8 j=0 9 while imaxlen or (curlen == maxlen and sd
再补充一个java实现:
1 class Solution { 2 public String findLongestWord(String s, Listd) { 3 String longestWord = ""; 4 for (String target : d) { 5 int l1 = longestWord.length(), l2 = target.length(); 6 if (l1 > l2 || (l1 == l2 && longestWord.compareTo(target) < 0)) { 7 continue; 8 } 9 if (isSubstr(s, target)) {10 longestWord = target;11 }12 }13 return longestWord;14 }15 16 private boolean isSubstr(String s, String target) {17 int i = 0, j = 0;18 while (i < s.length() && j < target.length()) {19 if (s.charAt(i) == target.charAt(j)) {20 j++;21 }22 i++;23 }24 return j == target.length();25 }26 }