day48—双指针-通过删除字母匹配到字典最长单词(LeetCode-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
  • sdictionary[i] 仅由小写英文字母组成

解决方案:

1、依题目要求,先给字典内的单词排序,同等长度ASCII值小的优先(即a<b)

2、双指针:当 si != dictionaryxj,我们使 i 指针右移,i 一直处于移动中,直到找到 s 中第一位与 dictionaryxj 对得上的位置, j 才右移去匹配下一个字符。如此循环。

3、验证长度即可返回对应单词字符。

函数源码:

cpp 复制代码
class Solution {
public: 
    string findLongestWord(string s, vector<string>& dictionary) {
        
        sort(dictionary.begin(),dictionary.end(),[](string& a,string& b){
            if(a.length()==b.length())  return a<b;
            return a.length()>b.length();
        });

        for(int x=0;x<dictionary.size();x++){
            string str=dictionary[x];
            int i=0,j=0;
            
            while(i<str.length()&&j<s.length()){
                if(str[i]==s[j])    i++;
                j++;
                
            }
            if(i==str.length()) return str;
            
        }
        return string();

    }
};
相关推荐
Navigator_Z9 小时前
LeetCode //C - 1206. Design Skiplist
c语言·算法·leetcode
码行山野赴时序归途9 小时前
三道经典数组题:从暴力到最优的算法思维
c语言·开发语言·数据结构·算法·leetcode
徐小夕10 小时前
3分钟从想法到Agent上线:我们开源了一款AI可视化工作流“IDE”
前端·算法·github
sel_911 小时前
【强化学习】Hands-on Modern RL项目实践|OPD 算法完整解析
人工智能·深度学习·算法·机器学习·语言模型
Navigator_Z12 小时前
LeetCode //C - 1209. Remove All Adjacent Duplicates in String II
c语言·算法·leetcode
ShineWinsu14 小时前
对于 C++:C++14中从变量模板、泛型 Lambda 到并发与字面量的解析
c++·算法
土司大王14 小时前
LeetCode hot100——合并两个有序链表
算法·leetcode·链表
码行山野赴时序归途14 小时前
算法效率的度量(上):时间复杂度中的对数思维
c语言·数据结构·算法
算AI15 小时前
基于LLM的无人机仿真测试:新方法竞赛夺佳绩
人工智能·深度学习·算法·机器学习·ai