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);
    }
}
相关推荐
码农小韩19 小时前
基于Linux的C++学习——指针
linux·开发语言·c++·学习·算法
wen__xvn20 小时前
第 34 场 蓝桥·算法入门赛·百校联赛
算法
ASD125478acx20 小时前
超声心动图心脏自动检测YOLO11-NetBifPN算法实现与优化
算法
无限进步_20 小时前
【C语言&数据结构】对称二叉树:镜像世界的递归探索
c语言·开发语言·数据结构·c++·git·算法·visual studio
星辞树21 小时前
揭秘阿里 DIN:当深度学习遇上“千物千面”
算法
刘立军21 小时前
如何选择FAISS的索引类型
人工智能·算法·架构
小芒果_0121 小时前
整理归并排序
c++·算法·排序算法·信息学奥赛
牛三金21 小时前
匿踪查询沿革-Private Information Retrieval(PIR)
算法·安全
德育处主任21 小时前
『NAS』在群晖部署一个文件加密工具-hat.sh
前端·算法·docker
星辞树21 小时前
从 L1/L2 到 Dropout:深度解析正则化,为何推荐系统“只能练一次”?
算法