Leetcode之Longest Word in Dictionary through Deleting 问题

来源:互联网 发布:医院网络咨询话术 编辑:程序博客网 时间:2024/05/21 17:29

问题描述:

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical(字典序) order. If there is no possible result, return the empty string.

Note:

  1. All the strings in the input will only contain lower-case letters.
  2. The size of the dictionary won't exceed 1,000.
  3. The length of all the strings in the input won't exceed 1,000.

示例一:

Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]

Output:
"apple"

示例二:

Input:
s = "abpcplea", d = ["a","b","c"]

Output:
"a"

问题来源:Longest Word in Dictionary through Deleting(详细地址:https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/description/)

思路分析:

解法一:我们可以遍历字典里的每个单词dictword,同时,我们用指针i来标记每个dictword里面的每个字符。如果i指向的每个字符和字符串s中的每个字符相对应的话,我们就将i移动到下一个字符。当i指向了该单词的最末尾的时候(严格来讲是i=dictword.length()的时候),我们就可以和目前存下来的最长的单词(用longest来存储)比较了。如果当前的单词dictword的长度比目前的最长的单词的长度要长,或者说dictword的长度等于longest,并且它在字典里要更靠前(我们使用compareTo()来判断),我们就需要更新最长字典单词longest了。

解法二:另外,discuss里面给出了一种排序的方法,它的排序原则就是:首先按照长度的升序排序,如果长度相等的话,我们就按照字典序的升序来排序,所以代码就是:

Collections.sort(d, (a, b) -> a.length() != b.length() ? -Integer.compare(a.length(), b.length()) : a.compareTo(b));

       这样,我们排序出来的字典单词就是按照题目给定的顺序排列了,所以寻找最长的单词的话,我们就只需要一个一个往后匹配就行了,匹配过程其实是和上面是一样的,每遍历一个单词,我们比较s中的每个字符和给定单词的每个字符(用i来指定每个字符),当i指向了最末尾,我们就直接返回了,无需再遍历后面的单词dictword了。

代码:

没有排序的方法:


排序的方法(带上了compareTo()方法的源码):


String的compareTo()方法:




阅读全文
0 0
原创粉丝点击