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);
    }
}
相关推荐
倒头就睡的小比特3 天前
算法竞赛C++常用的STL
c++·算法
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼3 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
旖旎夜光3 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark3 天前
大规模并行计算中的负载均衡算法研究4
算法
Because_of_Her13 天前
并查集-听课笔记
笔记·算法·并查集
码流子3 天前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构
another heaven3 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
wzdark3 天前
从算法设计模式看编程思维的抽象能力4
算法
2601_962218613 天前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法