leetcode ——匹配子序列的单词数

题目:

给定字符串 s 和字符串数组 words, 返回 words[i] 中是s的子序列的单词个数

字符串的 子序列 是从原始字符串中生成的新字符串,可以从中删去一些字符(可以是none),而不改变其余字符的相对顺序。

  • 例如, "ace""abcde" 的子序列。

示例 1:

复制代码
输入: s = "abcde", words = ["a","bb","acd","ace"]
输出: 3
解释: 有三个是 s 的子序列的单词: "a", "acd", "ace"。
Example 2:
输入: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]
输出: 2

代码:

java 复制代码
import java.util.ArrayList;
import java.util.List;

class Solution1 {

    public static void main(String[] args) {
        String s = "abcde";
        String[] words = {"a","bb","acd","ace"};
        System.out.println(numMatchingSubseq(s, words));

    }
    public static int numMatchingSubseq(String s, String[] words) {
        // 创建一个数组,用于存放26个英文字母的位置
        List<Integer>[] pos = new List[26];
        for(int i = 0; i < 26; i++){
            pos[i] = new ArrayList<Integer>(); // 初始化每个字母位置的列表
        }

        for(int i = 0; i < s.length(); i++){
            pos[s.charAt(i) - 'a'].add(i);

        }
        // 初始化最终结果 
        int res = words.length;

        for(String w : words){
            if(w.length() > s.length()){
                res--;
                continue;
            }
            int p = -1;// 用于记录上一个字符在S中出现的位置
            for(int i = 0; i < w.length(); i++){
                char c = w.charAt(i);
                // 如果当前字符c在s中没有出现,或者c在s中最后出现的位置不大于p,则w不是s的子序列
                if(pos[c-'a'].isEmpty() || pos[c-'a'].get(pos[c - 'a'].size()-1) <=p ){
                    res--;
                    break;
                }
                p = binarySearch(pos[c - 'a'], p);
            }
        }
        return res;

    }


    public static int binarySearch(List<Integer> list, int tagert){
        int left = 0;
        int right = list.size()-1;
        while(left < right){
            int mid =(left + right)/2;
            if(list.get(mid) < tagert){
                left = mid + 1 ;
            }else{
                right = mid ;
            }
        }
        return list.get(left);
    }
}
相关推荐
HjhIron7 小时前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩8 小时前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹9 小时前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术13 小时前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望15 小时前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
黄敬峰15 小时前
面试必刷:从JS底层包装类到双指针,彻底搞懂字符串与回文算法
算法
地平线开发者1 天前
J6B vio scenario sample
算法
BothSavage2 天前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn2 天前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法