力扣题:子序列-12.27

发布时间:2023年12月20日

力扣题-12.27

[力扣刷题攻略] Re:从零开始的力扣刷题生活

力扣题1:524. 通过删除字母匹配到字典里最长单词

解题思想:首先先遍历数据获得可能的答案,再对答案进行遍历选择出长度最长的且字母序最小的字符串

在这里插入图片描述

class Solution(object):
    def findLongestWord(self, s, dictionary):
        """
        :type s: str
        :type dictionary: List[str]
        :rtype: str
        """
        answer = []
        for i in range(len(dictionary)):
            j = 0
            k = 0
            while j<len(s) and k<len(dictionary[i]):
                if s[j] == dictionary[i][k]:
                    j +=1
                    k +=1
                else:
                    j +=1
            if k == len(dictionary[i]):
                answer.append(dictionary[i])
        maxlen = 0
        result = ''
        for i in range(len(answer)):
            if len(answer[i]) > maxlen:
                result = answer[i]
                maxlen = len(answer[i])
            elif len(answer[i]) == maxlen:
                for char1, char2 in zip(answer[i], result):
                    if char1 < char2:
                        result = answer[i]
                        break
                    elif char1 > char2:
                        break
        return result
class Solution {
public:
    string findLongestWord(string s, vector<string>& dictionary) {
        std::vector<std::string> answer;

        for (const auto& word : dictionary) {
            int j = 0, k = 0;
            while (j < s.length() && k < word.length()) {
                if (s[j] == word[k]) {
                    j++;
                    k++;
                } else {
                    j++;
                }
            }
            if (k == word.length()) {
                answer.push_back(word);
            }
        }

        int maxlen = 0;
        std::string result = "";
        for (const auto& word : answer) {
            if (word.length() > maxlen) {
                result = word;
                maxlen = word.length();
            } else if (word.length() == maxlen) {
                for (int i = 0; i < word.length(); ++i) {
                    if (word[i] < result[i]) {
                        result = word;
                        break;
                    } else if (word[i] > result[i]) {
                        break;
                    }
                }
            }
        }

        return result;
    }
};
文章来源:https://blog.csdn.net/yumeng3866/article/details/134983680
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。