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);
    }
}
相关推荐
小安同学iter1 天前
SQL50+Hot100系列(11.9)
算法·leetcode·职场和发展
炼金士1 天前
基于多智能体技术的码头车辆最快行驶路径方案重构
算法·路径规划·集装箱码头
小刘max1 天前
最长递增子序列(LIS)详解:从 dp[i] 到 O(n²) 动态规划
算法·动态规划
谢景行^顾1 天前
数据结构知识掌握
linux·数据结构·算法
235161 天前
【JVM】Java为啥能跨平台?JDK/JRE/JVM的关系?
java·开发语言·jvm·spring boot·后端·spring·职场和发展
ShineWinsu1 天前
对于数据结构:堆的超详细保姆级解析——下(堆排序以及TOP-K问题)
c语言·数据结构·c++·算法·面试·二叉树·
DuHz1 天前
基于时频域霍夫变换的汽车雷达互干扰抑制——论文阅读
论文阅读·算法·汽车·毫米波雷达
hetao17338371 天前
ZYZ28-NOIP模拟赛-Round4 hetao1733837的record
c++·算法
Nebula_g1 天前
C语言应用实例:解方程(二分查找)
c语言·开发语言·学习·算法·二分查找·基础
少许极端1 天前
算法奇妙屋(十)-队列+宽搜(BFS)
java·数据结构·算法·bfs·宽度优先·队列