力扣题:子序列-12.27

力扣题-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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值