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、双指针:当 s[i] != dictionary[x][j],我们使 i 指针右移,i 一直处于移动中,直到找到 s 中第一位与 dictionary[x][j] 对得上的位置, 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();

    }
};
相关推荐
放羊郎6 小时前
基于ORB-SLAM2算法的优化工作
人工智能·算法·计算机视觉
mask哥6 小时前
力扣算法java实现汇总整理(上)
java·算法·leetcode
如果'\'真能转义说7 小时前
OOXML 文档格式剖析:哈希、ZIP结构与识别
xml·算法·c#·哈希算法
梦梦代码精9 小时前
BuildingAI 上部署自定义工作流智能体:5 个实用技巧
大数据·人工智能·算法·开源软件
Zephyr_09 小时前
Leedcode算法题
java·算法
流年如夢10 小时前
栈和列队(LeetCode)
数据结构·算法·leetcode·链表·职场和发展
Hello.Reader11 小时前
算法基础(十)——分治思想把大问题拆成小问题
java·开发语言·算法
绛橘色的日落(。・∀・)ノ12 小时前
机器学习之评估与偏差方差分析
算法
消失的旧时光-194312 小时前
C语言对象模型系列(四)《Linux 内核里的 container_of 到底是什么黑魔法?》—— 一篇讲透 Linux 内核的“对象模型”核心技巧
linux·c语言·算法