day48—双指针-通过删除字母匹配到字典最长单词(LeetCode-524)

时间:2025-04-25 07:48:16

题目描述

给你一个字符串 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] 仅由小写英文字母组成

解决方案:

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

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

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

函数源码:

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();

    }
};