zoukankan      html  css  js  c++  java
  • [LeetCode] 524. Longest Word in Dictionary through Deleting

    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.

    Example 1:

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

    Example 2:

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

    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.

    通过删除字母匹配到字典里最长单词。

    给定一个字符串和一个字符串字典,找到字典里面最长的字符串,该字符串可以通过删除给定字符串的某些字符来得到。如果答案不止一个,返回长度最长且字典顺序最小的字符串。如果答案不存在,则返回空字符串。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路是双指针,类似于392题找子序列。因为 S 删除字母是无序的,所以只能通过判断子序列的方式来看d中的每个单词是不是由 S 而来。如果你找到一个单词了,之后再有一个单词,他也是 S 的子序列的时候,需要用 str.compareTo() 额外判断 str 的字典序是否比 res 小,若是则替换 res,从而得到字典序最小的结果。

    时间O(n^2)

    空间O(1)

    Java实现

     1 class Solution {
     2     public String findLongestWord(String s, List<String> d) {
     3         String res = "";
     4         for (String str : d) {
     5             if (isSubsequence(str, s)) {
     6                 if (str.length() > res.length() || (str.length() == res.length() && str.compareTo(res) < 0)) {
     7                     res = str;
     8                 }
     9             }
    10         }
    11         return res;
    12     }
    13 
    14     private boolean isSubsequence(String s, String t) {
    15         if (s == null || s.length() == 0) {
    16             return true;
    17         }
    18         int i = 0;
    19         int j = 0;
    20         while (i < s.length() && j < t.length()) {
    21             if (s.charAt(i) == t.charAt(j)) {
    22                 i++;
    23             }
    24             j++;
    25         }
    26         return i == s.length();
    27     }
    28 }

    相关题目

    392. Is Subsequence

    524. Longest Word in Dictionary through Deleting

    720. Longest Word in Dictionary

    LeetCode 题目总结

  • 相关阅读:
    字符串转换成整数
    回文字符串判断
    字符串包含
    翻转单词顺序VS左旋转字符串
    穷举子集合
    求S=a+aa+aaa+aaaa+aa...a的值
    数组元素去重
    找最长等差数列的长度
    Git pull and push
    Google 开发console查找元素或方法
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13894545.html
Copyright © 2011-2022 走看看