[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 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 three words in words that are a subsequence of S: "a", "acd", "ace".

Note:

  • All words in words and S will only consists of lowercase letters.
  • The length of S will be in the range of [1, 50000].
  • The length of words will be in the range of [1, 5000].
  • The length of words[i] will be in the range of [1, 50].

思路:

1、暴力法:

对于每个words[i],我们计算它是不是S的子序列。假设单词的平均长度为m,字典的大小为n,那么算法的时间复杂度就是O(mn),这个时间复杂度过不了大数据测试。

2、二分查找:

我们记录下来S中每个字符的出现次数。然后依次对于每个单词,在存储S中字符的有序数组中二分查找,每次找到之后,就从下一个位置上开始再找下一个字符。这样在处理每个words[i]的时候,我们是跳着走的,而不是顺序走的,就将原来判断一个word是不是S的子序列的时间复杂度从O(m)降低到了O(logm)这个量级。

代码:

1、暴力法:

class Solution {
public:
    int numMatchingSubseq(string S, vector<string>& words) {
        int ret = 0;
        for (int i = 0; i < words.size(); ++i) {
            if (isSubSeq(S, words[i])) {
                ++ret;
            }
        }
        return ret;
    }
private:
    bool isSubSeq(const string &s, const string &sub) {
        int i = 0, j = 0;
        while (i < sub.length() && j < s.length()) {
            if (sub[i] == s[j]) {
                ++i, ++j;
            }
            else {
                ++j;
            }
        }
        return i == sub.length();
    }
};

2、二分查找:

class Solution {
public:
    int numMatchingSubseq(string S, vector<string>& words) {
        vector<vector<int>> alpha (26);         // map from chars to their indices
		for (int i = 0; i < S.size (); ++i) {
            alpha[S[i] - 'a'].push_back (i);
        }
		int res = 0;
		for (const auto& word : words) {
			int x = -1;                         // the current index
			bool found = true;
			for (char c : word) {
				auto it = upper_bound (alpha[c - 'a'].begin (), alpha[c - 'a'].end (), x);
				if (it == alpha[c - 'a'].end ()) {
                    found = false;
                }
				else {
                    x = *it;
                }
			}
			if (found) {
                ++res;
            }
		}
		return res;
    }
};
手把手教你学AutoSAR - 总目录 鉴于近期较多博友问及微信群,如下可申请好友验证,请备注“autosar”,否则可能添加不通过。验证通过后,拉入讨论群。PS:本人鉴于工作事项可能不能及时回复问题,可在交流群内部和其他博友之间相互沟通交流经验。欢迎来到桃源乐游的《AutoSAR配置与实践》,以下为学习大纲,蓝色字体点击可跳转。 阅读详情

相关推荐

TSMC 40nm LP工艺下,新手画版图最容易踩的5个坑(附Cadence避坑指南)

本文详细解析了TSMC 40nm LP工艺下版图设计的5个常见陷阱,包括MOS管尺寸转换、DNW隔离、Guard Ring设计、金属布线和DRC检查。通过Cadence实战技巧和设计规则优化,帮助新手工程师规避典型错误,提升版图设计效率和质量。

weixin_26800111的博客 459

Leetcode每日随机2021/3/8

题 思 暴力可过 代码 class Solution { public int numMatchingSubseq(String s, String[] words) { int count = 0; for (String w : words) { if (isSubSeq(s, w)) { count++; } } return count; } private boolean isSubSeq(String s, String word) { i

Paul_1i的博客 177

UE4游戏开发:GameInstance与GameMode的实战应用与避坑指南

本文深入解析了UE4中GameInstance与GameMode的核心差异与实战应用。GameInstance作为贯穿游戏进程的全局单例,负责跨关卡数据持久化与系统管理;而GameMode则定义特定关卡内的游戏规则与逻辑,随关卡加载销毁。文章通过数据存储、动态模式切换及网络游戏等场景,提供了清晰的应用指南与常见避坑方案,帮助开发者构建更健壮的UE4游戏架构。

kubernetes8ctl的博客 230

LeetCode每日一题——792. 匹配子序列的单词数

给定字符串 s 和字符串数组 words, 返回 words[i] 中是s的子序列的单词个数 。 字符串的 子序列 是从原始字符串中生成的新字符串,可以从中删去一些字符(可以是none),而不改变其余字符的相对顺序。 例如, “ace” 是 “abcde” 的子序列。

hyk的博客 786

基于开源项目构建 CFS(网络靶场实战演练)平台

摘要:构建CFS网络靶场可使用多个开源组件组合,包括EVE-NG/GNS3或ContainerLab构建网络环境,Kasm提供工作空间,CALDERA+Atomic Red Team实现攻击模拟,DetectionLab建立防御环境,Malcolm/Arkime进行流量监控,CyRIS提供编排框架,Vulhub/DVWA创建漏洞靶标。关键在于通过API深度集成各组件,同时需注重安全隔离、资源规划及维护成本。建议开发统一管理平台,结合Ansible/Terraform实现自动化部署,打造定制化实战演练环境。(

深山技术宅的博客 1854

pytorchDataLoader中调整数据长度不一致问题(lstm等)

数据长度不一致 用pytorch做rnn的时候,如果输入数据不一样长,可以用两种方式解决。 一种是自定义collate方法, #自定义collate_fn dataloader.DataLoader(dataset,4,True,collate_fn=my_collate) 然后里面写数据和标签载入方式即可 def my_collate(batch): data = [item[0] for item in batch] target = [item[1] for item in batc

weixin_48174100的博客 7773

Is Subsequence(C++判断子序列)

Is Subsequence(C++判断子序列)

coolsunxu的博客 261

C# WinForm项目目录结构详解:从入门到精通(附常见问题解决方案)

本文详细解析了C# WinForm项目目录结构,从解决方案与项目基础结构到核心文件功能,再到关键目录解析,帮助开发者快速掌握WinForm项目组织方式。文章还提供了常见问题解决方案,如引用丢失、配置文件不生效等,是WinForm开发从入门到精通的实用指南。

dream的博客 648

LeetCode792:匹配子序列的单词数

题目描述 给定字符串 S 和单词字典 words, 求 words[i] 中是 S 的子序列的单词个数。 示例: 输入: S = “abcde” words = [“a”, “bb”, “acd”, “ace”] 输出: 3 解释: 有三个是 S 的子序列的单词: “a”, “acd”, “ace”。 注意: 所有在words和 S 里的单词都只由小写字母组成。 S 的长度在 [1, 50000]...

玉汝于成 1620

WVP+ZLM国标平台实战:从设备注册失败到视频播放黑屏,我遇到的5个典型问题与解法

部署WVP+ZLM国标视频平台时,设备注册失败、视频播放黑屏等问题常常让运维人员头疼不已。本文将基于真实运维场景,剖析五个最具代表性的故障案例,提供从网络配置到版本兼容性的全链路解决方案。

weixin_33178839的博客 362

面试问题总结——关于OpenCV(一)

整理了一下网上和我面试中遇到的关于OpenCV相关的问题。 其中因为我的简历中有个项目用到了特征点检测相关的知识,所以整理了SIFT/SURF和FLANN。 有些知识点也不深入,对于写的不对的地方,欢迎指正。 关于OpenCV的内容 1.OpenCV中cv::Mat的深拷贝和浅拷贝问题   深拷贝:分配新内存的同时拷贝数据,当被赋值的容器被修改时,原始容器数据不会改变。   浅拷贝:仅拷贝数据,当被赋值容器修改时,原始容器数据也会做同样改变。 OpenCV的Mat时,有几种赋值方式分别为:   深.

boss-dog 1万+

【LeetCode每日一题:792.匹配子序列的单词数~~~时间超限的双指针+改进优化的存储元素位置的二分查找】

【LeetCode每日一题:792.匹配子序列的单词数~~~时间超限的双指针+改进优化的存储元素位置的二分查找】给定字符串 s 和字符串数组 words, 返回 words[i] 中是s的子序列的单词个数。输入: s = “abcde”, words = [“a”,“bb”,“acd”,“ace”]解释: 有三个是 s 的子序列的单词: “a”, “acd”, “ace”。例如, “ace” 是 “abcde” 的子序列。实现代码2:参考官方实现的代码。

Coder_ljw的博客 242

【MicroPython编程-ESP32篇:设备驱动】-SHT31温度湿度传感器驱动

SHT31 是 Sensirion 的下一代温湿度传感器。 它建立在一个新的 CMOSens® 传感器芯片之上,该芯片是 Sensirion 新湿度和温度平台的核心。

视觉与物联智能 236

【LeetCode】792. Number of Matching Subsequences 解题报告(Python)

【LeetCode】792. Number of Matching Subsequences 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/number-of-matching-subsequences/description...

负雪明烛 2439

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

pscad IEEE标准系统搭建说明

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

LeetCode //C - 792. Number of Matching Subsequences

Summary: This solution efficiently counts the number of words in a given list that are subsequences of a string s. It uses a queue-based approach where words are initially grouped by their first character. As each character in s is processed, words waiting

Made in Code 1597

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

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

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

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] that is a subsequence of S. Example : Input: S = "abcde" words = ["...

qq_25336231的博客 251

[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

[leetcode]792. Number of Matching Subsequences

[leetcode]792. Number of Matching Subsequences Analysis 明天就是除夕啦—— [每天刷题并不难0.0] Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S. Explanation:...

weixin_32135877的博客 266

Leetcode 792. Number of Matching Subsequences (python)

Leetcode 792. Number of Matching Subsequences题目解法1:brutal force (TLE)解法2: 题目 解法1:brutal force (TLE) 用双指针法判断某个word是不是S的subsequence。 class Solution: def numMatchingSubseq(self, S: str, words: List[str]) -> int: def isSubsequence(word):

qq_37821701的博客 416

[LeetCode 792] Number of Matching Subsequences

Given stringSand adictionary of wordswords, find the number ofwords[i]that is a subsequence ofS. Example : Input: S = "abcde" words = ["a", "bb", "acd", "ace"] Output: 3 Explanation: There ...

ExcitedZhang的博客 194

【leetcode】792. Number of Matching Subsequences

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

很吵请安静 587

LeetCode: 792. Number of Matching Subsequences

题目: LeetCode: 792. Number of Matching Subsequences(https://leetcode.com/problems/number-of-matching-subsequences/description/)   class Solution { public int numMatchingSubseq(String S, String[]...

majinliang1234的博客 286

792. Number of Matching Subsequences**

792. Number of Matching Subsequences** https://leetcode.com/problems/number-of-matching-subsequences/description/ 题目描述 Given string S and a dictionary of words words, find the number of words[i] that ...

珍妮的选择的博客 239

【Leetcode】792. Number of Matching Subsequences

构造完序列自动机之后只需要将每个单词做一下判断即可。题目保证只含英文小写字母。思路是序列自动机,参考。和若干单词组成的数组。

数学、算法爱好者的博客 193

LeetCode 792. Number of Matching Subsequences 桶排序

Given string S and adictionary 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 three words in words that are a subsequence of S : "..

taoqick的专栏 263
上一篇: [Leetcode] 791. Custom Sort String 解题报告
下一篇: [Leetcode] 793. Preimage Size of Factorial Zeroes Function 解题报告
魔豆Magicbean
博客等级 码龄19年 146粉丝 742原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值