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

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

给你一个字符串 s 和一个字符串数组 dictionary ,找出并返回 dictionary 中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。

如果答案不止一个,返回长度最长且字典序最小的字符串。如果答案不存在,则返回空字符串。

示例 1:

输入:s = “abpcplea”, dictionary = [“ale”,“apple”,“monkey”,“plea”]
输出:“apple”
示例 2:

输入:s = “abpcplea”, dictionary = [“a”,“b”,“c”]
输出:“a”

提示:

1 <= s.length <= 1000
1 <= dictionary.length <= 1000
1 <= dictionary[i].length <= 1000
s 和 dictionary[i] 仅由小写英文字母组成

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {
public:
    bool isfindWord(string src, string obj){
        int src_point = 0, obj_point = 0;
        while(src_point < src.size()){
            if(src[src_point] == obj[obj_point]){
                src_point++;
                obj_point++;
            }
            else{
                src_point++;
            }
            if(obj_point == obj.size()){
                return true;
            }
        }
        return false;
    }
    string findLongestWord(string s, vector<string>& dictionary) {
        string ret = "";
        for(int i = 0; i < dictionary.size(); i++){
            if(isfindWord(s, dictionary[i]) && dictionary[i].size() >= ret.size()){                
                if (dictionary[i].size() > ret.size()){
                    ret = dictionary[i];
                }
                else{
                    (strcmp(dictionary[i].c_str(), ret.c_str()) == -1) ? ret = dictionary[i] : ret = ret;
                }
            }
        }
        return ret;
    }
};
class Solution:
    def isfindWord(self, src : str, obj : str) -> bool:
        sp = op = 0
        for i in range(len(src)):
            if src[sp] == obj[op]:
                sp, op = sp + 1, op + 1
            else:
                sp = sp + 1
            if op == len(obj):
                return True
        return False
    def findLongestWord(self, s: str, dictionary: List[str]) -> str:
        ret = ""
        for i in range(len(dictionary)):
            if self.isfindWord(s, dictionary[i]) and len(dictionary[i]) >= len(ret):
                if len(dictionary[i]) > len(ret):
                    ret = dictionary[i]
                else:
                    ret = dictionary[i] if dictionary[i] < ret else ret
        return ret
上一篇:NLP入门-Task4 自然语言处理


下一篇:524. 通过删除字母匹配到字典里最长单词