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.

 

 

 

 

思路:

思路比较基础,一个一个比较是否匹配,然后找出长度最长且字典序最小的字符串即可。首先匹配,用双指针,一个 i 遍历原数组,一个 j 指向当前比较的字典内数组,如果字符匹配,则 j 向后一格,如果 j 走到了终点则说明可以匹配,这里为了方便另写了一个函数用于匹配。然后有个小点是处理字典序,因为只有长度相等时才需要进行字典序排序,因此如果长度相等时,直接进行比较即可,不需要对原给定字典进行排序。

 

 

 

 

代码:

class Solution {
public:
    string findLongestWord(string s, vector<string>& d) {
        int count=0;
        string ans="";
        for(auto i:d)
        {
            if(check(s,i))
            {
                if(i.size()>count || (i.size()==count&&i<ans))
                {
                    count=i.size();
                    ans=i;
                }
            }
        }
        return ans;
    }
private:
    bool check(string &s, string &t)
    {
        int j=0;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]==t[j])
            {
                j++;
                if(j==t.size())
                    return true;
            }
        }
        return false;
    }
};

上一篇:C# Dictionary


下一篇:遍历 Dictionary,你会几种方式?