public class Solution { public string FindLongestWord(string s, IList<string> d) { 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; } }
https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/#/description
补充一个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 i<len(s) and j<len(sd): 10 if s[i]==sd[j]: 11 curlen += 1 12 if curlen == len(sd): 13 if curlen > maxlen or (curlen == maxlen and sd<longestword): 14 maxlen = curlen 15 longestword = sd 16 17 break 18 else: 19 i+=1 20 j+=1 21 else: 22 i+=1 23 return longestword
再补充一个java实现:
1 class Solution { 2 public String findLongestWord(String s, List<String> d) { 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 }