zoukankan      html  css  js  c++  java
  • 0524. Longest Word in Dictionary through Deleting (M)

    Longest Word in Dictionary through Deleting (M)

    题目

    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.

    题意

    给定字符串s和一个单词列表d,判断能否在s中删去若干个字符后得到d中的某一个单词,返回能得到的最长的单词。

    思路

    判断一个字符串s删去若干字符后能否得到字符串t,等价于判断t中所有字符是否在s中按顺序出现。遍历每一个单词,按照上述方法判断是否符合,最后选出最长的即可。


    代码实现

    Java

    class Solution {
        public String findLongestWord(String s, List<String> d) {
            String ans = "";
            int maxLen = 0;
    
            for (String word : d) {
                if (isValid(s, word) && (word.length() > maxLen || word.length() == maxLen && word.compareTo(ans) < 0 )) {
                    maxLen = word.length();
                    ans = word;
                }
            }
    
            return ans;
        }
    
        private boolean isValid(String s, String word) {
            int i = 0, j = 0;
            while (j < word.length() && i < s.length()) {
                char a = s.charAt(i), b = word.charAt(j);
                if (a == b) {
                    j++;
                }
                i++;
            }
            return j == word.length();
        }
    }
    
  • 相关阅读:
    ReportMachine打印条形码的问题
    性能测试基础知识
    jmeter请求参数中文乱码及无法读取CSV文件解决办法
    soapui学习
    java环境变量和查看安装路径
    python字典中显示中文
    Jmeter做webservices接口测试
    windows 上robot framework 读取sqlite3提示:OperationalError: unable to open database file错误
    c++ 复习练习
    笔记草稿。
  • 原文地址:https://www.cnblogs.com/mapoos/p/14432601.html
Copyright © 2011-2022 走看看