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

    https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/#/solutions

    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.
    Time Complexity: O(nk), where n is the length of string s and k is the number of words in the dictionary.
    An alternate, more efficient solution which avoids sorting the dictionary:
    
    public String findLongestWord(String s, List<String> d) {
        String longest = "";   // 用来比较的local
        for (String dictWord : d) {  // 题意: 顺序遍历
            int i = 0;               // 每次都得从target头部开始遍历
            for (char c : s.toCharArray())   // 判断字符串的每一个字母相等用toCharArray
                if (i < dictWord.length() && c == dictWord.charAt(i)) i++; 题意: 比较
    
          if (i == dictWord.length() && dictWord.length() >= longest.length()) //判断是否满足题意
             if (dictWord.length() > longest.length() || dictWord.compareTo(longest) < 0)
                 // 是否满足两点, 更新global, 学
    会s.compareTo(ss) 来比较字典顺序
         longest = dictWord;
      }
      return longest;
    }

      

  • 相关阅读:
    查看当前的数据和索引的总大小
    PXC安装
    [学习笔记]位运算
    PXC小结
    java算法集训代码填空题练习3
    mha配置参数详解
    [学习笔记]二分图
    Java 实现 蓝桥杯 等额本金
    账号权限问题导致 masterha_check_repl 检查失败
    [学习笔记]0/1分数规划
  • 原文地址:https://www.cnblogs.com/apanda009/p/7121213.html
Copyright © 2011-2022 走看看