• LeetCode——Longest Word in Dictionary through Deleting


    1. Question

    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:
    All the strings in the input will only contain lower-case letters.
    The size of the dictionary won't exceed 1,000.
    The length of all the strings in the input won't exceed 1,000.

    2. Solution

    直接用输入字符串去匹配字典中的每一个字符串。时间复杂度O(nk),n为字典中字符串的个数,k为输入字符串的长度。

    3. Code

    class Solution {
    public:
        string findLongestWord(string s, vector<string>& d) {
            string longest = "";
            for (string str : d) {
                int j = 0;
                for (int i = 0; i < s.length(); i++) {
                    if (s[i] == str[j])
                        j++;
                }
                // 字符串匹配完以及长度大于等于
                if (j == str.length() && str.length() >= longest.length()) {
                	// 要么更长,如果一样长,那么就看字典序
                    if (str.length() > longest.length() || str < longest)
                        longest = str;
                }
            }
            return longest;
        }
    };
    
  • 相关阅读:
    linux shell 总结
    python小结
    python与execl的读写
    利用burpsuits暴力破解登陆界面
    python之函数的使用
    Sublime text怎么识别input函数
    ping的禁止
    Hbase的配置与使用
    JAVA 利用反射自定义数据层框架
    JAVA实现网页上传头像
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7786516.html
Copyright © 2020-2023  润新知