zoukankan      html  css  js  c++  java
  • 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.
     1 public class Solution {
     2     public String findLongestWord(String s, List<String> d) {
     3         Comparator<String> comp = new Comparator<String>(){
     4           public int compare(String s1,String s2){
     5               if(s1.length()!=s2.length()){
     6                   return s2.length()-s1.length();
     7               }else{
     8                   return s1.compareTo(s2);
     9               }
    10           }  
    11         };
    12         Collections.sort(d,comp);
    13         for(String str:d){
    14             int i=0;
    15             for(char c:s.toCharArray()){
    16                 if(i<str.length()&&str.charAt(i)==c) i++;
    17             }
    18             if(i==str.length()) return str;
    19         }
    20         return "";
    21     }
    22 }
    23 //the run time complexity could be nlongn, the space complexity could be O(1);
     1 public class Solution {
     2     public String findLongestWord(String s, List<String> d) {
     3         String longest = "";
     4         for(String str:d){
     5             int i = 0;
     6             for(char c:s.toCharArray()){
     7                 if(i<str.length()&&str.charAt(i)==c) i++;
     8             }
     9             if(i==str.length()&&str.length()>=longest.length()){
    10                 if(str.length()>longest.length()||str.compareTo(longest)<0){
    11                     longest = str;
    12                 }
    13             }
    14         }
    15         return longest;
    16     }
    17 }
    18 //the run time could be O(nkaveragep),space complexity could be O(1);
  • 相关阅读:
    mysql通过一张表更新另一张表
    申请微信支付填错对公账号的解决办法
    radio 实现点击两次 第一次点击选中第二次点击取消
    C#修改下拉框选项的高度
    Centos7 用yum命令安装LAMP环境(php+Apache+Mysql)以及php扩展
    php备份数据库
    windows环境下 composer 的安装与使用
    PHP获取多维数据的交集与差集
    JS 图片懒加载
    搭建 window + nginx + php 开发环境
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6906702.html
Copyright © 2011-2022 走看看