LeetCode 524. 通过删除字母匹配到字典里最长单词

给定一个字符串和一个字符串字典,找到字典里面最长的字符串,该字符串可以通过删除给定字符串的某些字符来得到。如果答案不止一个,返回长度最长且字典顺序最小的字符串。如果答案不存在,则返回空字符串。

示例 1:

输入:
s = "abpcplea", d = ["ale","apple","monkey","plea"]

输出: 
"apple"

示例 2:

输入:
s = "abpcplea", d = ["a","b","c"]

输出: 
"a"

说明:

  1. 所有输入的字符串只包含小写字母。
  2. 字典的大小不会超过 1000。
  3. 所有输入的字符串长度不会超过 1000。

思路:首先对字典按照输出要求进行排序,即按照长度逆序,对于长度相同的按照字典顺序小的排列,这样当我们找到第一个字符串以后就不需要继续匹配字符串了。匹配字符串的时候使用两个下标分别指向字符串和字典中的字符串。

class Solution {
public:  
    bool isWord(string pattern, string &srcStr){
        int i=0, j=0, pLen=int(pattern.size()), sLen=int(srcStr.size());
        while(i<pLen && j<sLen){
            if(pattern[i]==srcStr[j]){
                ++i;
                ++j;
            }
            else
                ++i;
        }
        
        if(j<sLen)
            return false;
        else
            return true;
    }    
   
    static bool compare(string &a, string &b){
        if(a.size()>b.size())
            return true;    
        else if(a.size()==b.size()){
            if(a<b)
                return true;
            else
                return false;
        }      
        else
            return false;
    }
  
    string findLongestWord(string s, vector<string>& d) {
        if(s.size()==0 || d.size()==0)
            return "";
                
        sort(d.begin(), d.end(), compare);
        
        for(int i=0;i<d.size();++i){
            if(isWord(s, d[i])){
                return d[i];
            }
        }
        
        return "";
    }
};

猜你喜欢

转载自blog.csdn.net/sinat_15723179/article/details/80897555