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

    原题链接在这里:https://leetcode.com/problems/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.

    题解:

    For each word in the string dictionary, try to compare it with s. If there is a char in s matching current pointed char in word, move the index. 

    If the index could move to end of word, it means word could be formed by deleting some characters of s.

    Then update res based on length lexicographical order of word.

    Time Complexity: O(m*n). m = s.length(). n = d.size().

    Space: O(1). regardless res.

    AC Java:

     1 class Solution {
     2     public String findLongestWord(String s, List<String> d) {
     3         if(s == null || d == null || d.size() == 0){
     4             return "";
     5         }
     6         
     7         String res = "";
     8         for(String word : d){
     9             int i = 0;
    10             for(char c : s.toCharArray()){
    11                 if(i<word.length() && c == word.charAt(i)){
    12                     i++;
    13                 }
    14             }
    15             
    16             if(i == word.length()){
    17                 if(res.length() < word.length()){
    18                     res = word;
    19                 }else if(res.length() == word.length() && res.compareTo(word)>0){
    20                     res = word;
    21                 }
    22             }
    23         }
    24         
    25         return res;
    26     }
    27 }
  • 相关阅读:
    《大道至简》读后感
    四大扩展欧几里得算法
    java8中使用函数式接口
    04_web基础(一)之tomcat介绍
    03_java基础(九)之综合练习与考核评估
    建站流程
    03_java基础(八)之static关键字与代码块
    (十)拒绝服务攻击工具包
    (九)拒绝服务攻击工具
    (八)拒绝服务–应用层DoS 攻击
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11403312.html
Copyright © 2011-2022 走看看