zoukankan      html  css  js  c++  java
  • 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;
        }
    };
    
  • 相关阅读:
    家庭记账本APP开发准备(二)
    使用花生壳5做内网穿透
    课堂练习之可视化的强化版
    第五周总结
    课堂练习之疫情可视化
    第四周总结
    第三周总结
    第二周总结
    课堂练习之最大子数组
    软工第二学期开课博客
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7786516.html
Copyright © 2011-2022 走看看