leetcode 792. Number of Matching Subsequences(匹配的子串数量)

leetcode 792. Number of Matching Subsequences | 792. 匹配子序列的单词数(Java) 题目 https://leetcode.com/problems/number-of-matching-subsequences/ 题解 一看数据规模,普通暴力解法肯定超时了。想了半天怎么用 Trie,没有想出来,于是直奔评论区。 作者的代码很简洁易懂,看完之后自己写了一遍。 class Solution { public int numMatchingSubseq(String s, String[] words) { ArrayList<StringBuilder&gt 阅读详情

Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

For example, “ace” is a subsequence of “abcde”.

Example 1:

Input: s = “abcde”, words = [“a”,“bb”,“acd”,“ace”]
Output: 3
Explanation: There are three strings in words that are a subsequence of s: “a”, “acd”, “ace”.
Example 2:

Input: s = “dsahjpjauf”, words = [“ahjpjau”,“ja”,“ahbwzgqnuk”,“tnmlanowax”]
Output: 2

判断words里面有几个是s的子串。
子串指字母都在s里,且保持相对顺序,在s中不一定是连续的。

思路:

1.binary search
可以直接用Brute force,每个word都遍历一遍s,判断是不是子串,
但这种方法在大量重复word的时候会TLE,可用一个hashmap保存下每个word判断的结果。

但是每次遍历s用的都是线性时间复杂度,用binary search的话可以把这种判断子串的时间缩短到O(logn)

具体怎么做,首先把s中的字母出现的位置都保存在list里,因为字母只有26个,所以用下标i对应第 i 个字母,
字母对应的位置保存list, 即各字母都在什么位置出现。

然后遍历word的时候,只需要顺次找到字母出现的位置,
找到前一个字母出现的位置之后,记下下标left, 下一次在left+1往后的位置找下一个字母,找不到就返回false.

同时,用2个hashset记录下已经判断过是子串和不是子串的word.

class Solution {
    List<List<Integer>> pos;
    HashSet<String> set = new HashSet<>();
    HashSet<String> not = new HashSet<>();
    
    public int numMatchingSubseq(String s, String[] words) {
        int res = 0;
        pos = new ArrayList<>();
        for(int i = 0; i < 26; i ++) {
            pos.add(new ArrayList<Integer>());
        }
        
        //保存每个字母出现的位置
        for(int i = 0; i < s.length(); i++) {
            pos.get(s.charAt(i) - 'a').add(i);
        }
        
        for(String word : words) {
            if(isMatch(word)) {
                set.add(word);
                res ++;
            } else {
                not.add(word);
            }     
        }
        return res;
    }
    
    boolean isMatch(String word) {
        if(set.contains(word)) return true;
        if(not.contains(word)) return false;
        int left = -1;
        
        for(char ch : word.toCharArray()) {
            List<Integer> curPos = pos.get(ch - 'a');
            //找left+1,即下一index,可能会找不到,但是我们要的不是确切的left+1,而是比它大的即可,
            //所以要找到需要插入的位置,即返回的负的index
            int index = Collections.binarySearch(curPos, left+1);
            if(index < 0) index = -index -1;
            if(index >= curPos.size()) return false;
            left = curPos.get(index);
        }
        return true;
    }
}

2.queue

上面方法一是对每个单词,都要遍历一次s来进行匹配,
那么有没有只遍历一次s,同时达到匹配所有单词的效果?

如果想达到这种效果,第一直觉应该是每遍历到s的一个字母,我们都要去匹配每个单词,
单词中如果有字母和s的这个字母匹配,就把单词的遍历下标+1,
那么每个单词都应该有一个遍历的下标,这么多下标要怎么维护呢?

定义一个Item, 里面是单词和目前遍历到的下标。

首先把words做一个处理,把words中每个单词首字母对应的位置加入一个queue,
这个queue保存的是现在每个单词和它们的遍历下标:0,

后面queue保存的是和当前s遍历到的字母 匹配的所有item(单词和它们相应的字母下标)。

然后遍历s中的字母,每个字母取出对应的queue, queue里面有所有以这个字母开头的单词,
字母匹配之后,把对应单词的当前下标+1,也就是下一次将匹配的字母下标,
如果下标和单词长度一致,认为已经遍历完,该单词是子串,结果+1.

class Solution {
    class Item {
        String word;
        int index;
        public Item (String s, int i) {
            word = s;
            index = i;
        }
    }
    public int numMatchingSubseq(String S, String[] words) {
        Queue<Item>[] dict = new Queue[26];
        for (int i = 0; i < dict.length; i++) {
            dict[i] = new LinkedList<>();
        }

        for (String word :words) {
            if (word.length() > 0) {
                dict[word.charAt(0) - 'a'].add(new Item(word, 0));
            }
        }

        int count = 0;
        for (char c : S.toCharArray()) {
            Queue<Item> queue = dict[c - 'a'];
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Item top = queue.remove();
                top.index++;
                if (top.index == top.word.length()) {
                    count++;
                } else {
                    dict[top.word.charAt(top.index) - 'a'].add(top);
                }
            }
        }

        return count;
    }
}
别怕,“卷积”其实很简单 首先给大家讲一个关于卷积的小故事:小明是杭州某互联网大厂的员工,每天996十分辛苦,但小明最近爱上了打台球,经常不在工位。这天,小明的主管让小明改一个需求,小明却到楼下找产品部小丽打台球去了,被主管发现,他非常气愤,扇了小明一巴掌(注意,这就是输入信号,脉冲)。于是小明脸上会渐渐地(贱贱地)鼓起来一个包,小明的脸就是一个系统,而鼓起来的包就是小明的脸对巴掌的响应。好,这样就和信号系统建立起来意义对应的联系。 阅读详情

相关推荐

MATLAB MinGW-w64 C/C++ 编译器 手动安装配置

根据Matlab版本与MinGW版本对应关系,手动安装、配置并测试MinGW

zjh2883的博客 7366

(七)数据结构-串

串(string)是由零个或多个字符组成的有序序列,一般记为S=‘a1a2a3…an’(n>=10)其中S是串名,单括号括起来的字符序列是串的值;ai可以是字母、数字或者其他字符;串中字符的个数n称为串的长度;当n=0时的串称为空串;......

weixin_45579930的博客 843

MT5交易软件系统源码

Manager配置的功能及权限:管理客户、开户,销户、入金、信用额度、修改定单、人工交易报表、设定点差、强制平仓、修改密码,设定持仓交割单或挂单小止盈止损点数;26、修改价格 27、更改K线图历史价格 28、同步历史数据;2、系统设置 3、交易管理 4、交易柜台 5、价格更改 6、多台服。务器联机 7、恢复交易历史 8、数据源调整 9、备份服务调整 10、交易市场设定 11、交易单更改 12、平台时间设定(全世界) 13、可添加商品;15、设置商品利息;独立主机(服务器、VPS、VM)

tutujunjun的博客 912

使用kmp算法计算模式串在主串中有多少个完全匹配的子串

在做这道题时,设置一个count变量,通过if语句进行判断模式串是否已经完全匹配一次。 int count_kmp(char *s, char *p,int next[]){ int count = 0,i = 0; int j = 0; int sLen = strlen(s); int pLen = strlen(p); while(i<sLen) //因为是在主串中匹配个数,所以不能用模式串的长度作为判断循环的条件 { if (j == -1 || s[i] == p[j])

lookmeli的博客 2384

Q学习(Q-learning)入门小例子及python实现

一、从马尔科夫过程到Q学习 # 有一定基础的读者可以直接看第二部分 Q学习(Q-learning)算法是一种与模型无关的强化学习算法,以马尔科夫决策过程(Markov Decision Processes, MDPs)为理论基础。 标准的马尔科夫决策过程可以用一个五元组<S,A,P,R,γ>表示,其中: S是一个离散有界的状态空间; A是一个离散的动作空间; P为状态转...

wlm_py的博客 4万+

VS配置RTKLIB(卫星定位开源代码)环境

@RTKlib代码调试教程-Visual Studio 2019 你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。 ##RTKLIB-rtklib_2.4.3 提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 @RTKlib代码调试教程-Visual Studio 2019 提示:这里可以添加本文要记录的大概内容: 例如:随着人工智能的不断发展,机器学习这门技

qq_42209977的博客 4494

LWC 74: 792. Number of Matching Subsequences

LWC 74: 792. Number of Matching Subsequences 传送门:792. Number of Matching Subsequences Problem: Given string S and a dictionary of words words, find the number of words[i] that is a subsequence o...

Demon-初来驾到 1430

ParallelsDesktop 安装 CentOS-6.9-x86_64-minimal 教程

安装参考 tools没做 想安装的可以参考这个 mac 本机环境: 系统:macOS Catalina version 10.15.6 虚拟机软件:parallels Desktop 15 for Mac( Parallels Desktop-15.1.4(47270)) Centos镜像: CentOS-6.9-x86_64-minimal.iso https://mirrors.aliyun.com/centos-vault/6.8/isos/x86_64/ http://vault.centos.

爱吃鱼的小明的博客 958

792. Number of Matching Subsequences

Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.Example : Input: S = "abcde" words = ["a", "bb", "acd", "ace"] Output: 3 Explanation: There are t

xdhc的博客 196

技术面 - 手撕算法题整理

这篇博客整理了华为OD面试中涉及的算法题,包括LeetCode热门题目、OD原题和需要手写的算法,如二分查找、冒泡排序等。建议优先刷"hot100"的LeetCode题目,全刷OD原题,以及掌握手撕算法的基本原理。

m0_73659489的博客 1034

SKUA-GOCAD入门教程-第四节

本文介绍了软件界面中的几个关键功能模块。控制菜单允许用户通过按钮添加视图、对象窗口、工作流平台等工具到任务栏,并支持快速搜索。页面布局以任务为导向,包含3D、2D视图、工具栏等,用户可自定义页面和布局。对象窗口用于浏览和处理数据,如钻孔、断层等,支持显示、隐藏、分组和过滤数据。3D查看器的数据浏览器对象窗口包含列表、对象等,建模数据通常位于未分配对象窗口中。本文旨在帮助用户熟悉软件界面,特别是3D视图窗口和对象管理窗口,以便更高效地进行数据导入和建模操作。

江洋大葱的博客 1077

leetcode 792. Number of Matching Subsequences

leetcode 792. Number of Matching Subsequences leetcode 792. Number of Matching Subsequences 题目描述 解答思路 代码 题目描述 Given string S and a dictionary of words words, find the number of words[i] t...

pjq的博客 1325

Windows10下安装VMware16虚拟机

由于本人系统为Windows 10 家庭中文版,无法安装Linux子系统WSL,虽然网上也有强制安装的方法,但为保险起见,还是把之前的VMware虚拟机重新进行安装,并浅浅记录一下安装过程。

沉香best的博客 870

[leetcode] 792. Number of Matching Subsequences

Description Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S. Example : Input: S = "abcde" words = ["a", "bb", "acd", "ace"] Output: 3 Explanati...

Learning from the mistakes 284

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

LeetCode792. Number of Matching Subsequences(匹配子序列的单词数)

`words`中是`S`的子串的数量

grllery的博客 457

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

[LeetCode] Distinct Subsequences

class Solution { public: int numDistinct(string S, string T) { // Start typing your C/C++ solution below // DO NOT write int main() function int m = T.size(); int n

lyangpku的专栏 701

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

[Leetcode] 792. Number of Matching Subsequences 解题报告

题目: Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S. Example : Input: S = "abcde" words = ["a", "bb", "acd", "ace"] Output: 3 Explanatio

魔豆(Magicbean)的博客 524

【天梯】子字符串个数匹配 (15 分)

#include<bits/stdc++.h> using namespace std; int main() { string a,b; getline(cin,a); cin>>b; for(int i=0;a[i];i++) { if(a[i]>='A'&&a[i]<='Z') a[i]=a[i]+32; if(!(a[i]>='a'&&a[i]<='z')) a[i]=' '; } ..

karshey的博客 776

排序算法十:桶排序

排序算法十:桶排序 声明:引用请注明出处http://blog.csdn.net/lg1259156776/ 引言 在我的博文《“主宰世界”的10种算法短评》中给出的首个算法就是高效的排序算法。本文将对排序算法做一个全面的梳理,从最简单的“冒泡”到高效的堆排序等。 系列博文的上一篇讲述了基数排序,本文讲...

weixin_30530339的博客 375

leetcode#792. Number of Matching Subsequences

792. Number of Matching Subsequences Problem Description Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S. Analysis and Solution 基本思路是对wor...

Faldict的博客 740

LeetCode_115---Distinct Subsequences

Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence of a string is a new string which is formed from the original string by deleting some (can be none)

MohnSnow,Winter is Coming!!! 495

【leetcode】792. Number of Matching Subsequences

给定字符串S和一个字符串数组,求数组中有多少个字符串是S的子字符串,子字符串的定义是可以母串可以通过删减元素成为子串。 方法一: 首先想到的就是双指针法,对字符串中的每个元素进行匹配操作,来判断是否为字字符串,想想都知道会超时的。 class Solution: def numMatchingSubseq(self, S, words): """ :typ...

很吵请安静 592

Number of Matching Subsequences--leetcode 792

[Number of Matching Subsequences]  792-问题描述Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.Example :Input: S = "abcde"words = ["a", "bb", "acd", ...

drunkpragrammer的博客 888

字符串匹配个数

程序功能说明:在输入的字符串中,找到指定字符串“virus”在该字符串中包含子串所有可能性个数。 例如:输入:virusttviruse,输出结果:23。 #include&lt;stdio.h&gt; #include&lt;string.h&gt; long f(int n); //查询匹配的个数 int find(char *arr, char *temp, int len_a, in...

haojiefenglang的博客 1927
上一篇: RGB+深度图像 语义分割paper阅读笔记(ICRA2021)
下一篇: leetcode 92. Reverse Linked List II(链表逆序II)
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址