leetcode524

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 }

 

转载于:https://www.cnblogs.com/asenyang/p/6939632.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值