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);
    }
}
相关推荐
爱理财的程序媛1 小时前
openclaw 盯盘实践
算法
MobotStone5 小时前
Google发布Nano Banana 2:更快更便宜,图片生成能力全面升级
算法
颜酱8 小时前
队列练习系列:从基础到进阶的完整实现
javascript·后端·算法
用户5757303346248 小时前
两数之和:从 JSON 对象到 Map,大厂面试官到底在考察什么?
算法
程序猿追8 小时前
“马”上行动:手把手教你基于灵珠平台打造春节“全能数字管家”
算法
ZPC82101 天前
docker 镜像备份
人工智能·算法·fpga开发·机器人
ZPC82101 天前
docker 使用GUI ROS2
人工智能·算法·fpga开发·机器人
琢磨先生David1 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
颜酱1 天前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
多恩Stone1 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc