zoukankan      html  css  js  c++  java
  • leetcode524- Longest Word in Dictionary through Deleting- medium

    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.

    算法。基本思路是遍历整个词典里的单词,拿着这个单词word去给入的新字符串s找每个word内字母有没有按顺序出现过。检查按顺序的方法有两种

    1.用indexOf()每次更新。每次在后一点的位置开始找word的下一个字母。

    2.(更简单)通过遍历s内的每个字母不断+1,同时一个指针指着word的字母偶尔+1,如果找到字符对上了,word的指针加上去,等到s的字母都走完了如果word的指针还没走到最后的话,就不合格。最后合格的word打个擂台就好。

    时间复杂度:O(nk)。n是字符串长度,k是字典里单词个数。

    细节:要求字典序比较方法是直接s1.compareTo(s2)

    实现1:用indexOf的

    class Solution {
        public String findLongestWord(String s, List<String> d) {
            String result = "";
            if (s == null || d == null || d.size() == 0) {
                return result;
            }
    
            for (String word : d) {
                int index = -1;
                int i = 0;
                for (i = 0; i < word.length(); i++) {
                    index = s.indexOf(word.charAt(i), index);
                    if (index == -1) {
                        break;
                    }
                    index++;
                }
                if (index != -1 && (word.length() > result.length() 
                                    || word.length() == result.length() && word.compareTo(result) < 0)) {
                        result = word;
                }
            }
            return result;
        }
    }

    实现2:指针遍历

    public String findLongestWord(String s, List<String> d) {
        String longest = "";
        for (String dictWord : d) {
            int i = 0;
            for (char c : s.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)
                    longest = dictWord;
        }
        return longest;
    }
  • 相关阅读:
    NTC温度检测程序(转)
    基于GPS的经纬度、方位角、距离、航向计算及基于单目视觉的距离计算!
    GPS速度和航向计算(转)
    NOR、 NAND、Raw Flash和 Managed Flash的区别(转)
    FreeModbus V1.6 主机使用说明(转)
    只要单片机具有真正唯一ID,就可以让加密坚不可摧(转)
    Java 给Word添加数字签名
    Java 获取Word中指定图片的坐标位置
    C#/VB.NET 自定义PPT动画路径
    在线编辑Excel——插入图表
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7985885.html
Copyright © 2011-2022 走看看