[LeetCode] Is Subsequence 是子序列
Given a string s and a string t, check if s is subsequence of t.
You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace" is a subsequence of "abcde" while "aec" is not).
Example 1:
s = "abc", t = "ahbgdc"
Return true.
Example 2:
s = "axc", t = "ahbgdc"
Return false.
Follow up:
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
这道题算比较简单的一种,我们可以用两个指针分别指向字符串s和t,然后如果字符相等,则i和j自增1,反之只有j自增1,最后看i是否等于s的长度,等于说明s已经遍历完了,而且字符都有在t中出现过,参见代码如下:
解法一:
class Solution {
public:
    bool isSubsequence(string s, string t) {
        int i = ;
        for (int j = ; j < t.size() && i < s.size(); ++j) {
            if (s[i] == t[j]) ++i;
        }
        return i == s.size();
    }
};
题目中的 Follow up 说如果有大量的字符串s,问我们如何进行优化。那么既然字符串t始终保持不变,我们就可以在t上做一些文章。子序列虽然不需要是连着的子串,但是字符之间的顺序是需要的,那么我们可以建立字符串t中的每个字符跟其位置直接的映射,由于t中可能会出现重复字符,所以把相同的字符出现的所有位置按顺序加到一个数组中,所以就是用 HashMap 来建立每个字符和其位置数组之间的映射。然后遍历字符串s中的每个字符,对于每个遍历到的字符c,我们到 HashMap 中的对应的字符数组中去搜索,由于位置数组是有序的,我们使用二分搜索来加快搜索速度,这里需要注意的是,由于子序列是有顺序要求的,所以需要一个变量 pre 来记录当前匹配到t字符串中的位置,对于当前s串中的字符c,即便在t串中存在,但是若其在位置 pre 之前,也是不能匹配的。所以我们可以使用 uppper_bound() 来二分查找第一个大于 pre 的位置,若不存在,直接返回 false,否则将 pre 更新为二分查找的结果并继续循环即可,参见代码如下:
解法二:
// Follow up
class Solution {
public:
bool isSubsequence(string s, string t) {
int pre = -, n = t.size();
unordered_map<char, vector<int>> char2pos;
for (int i = ; i < n; ++i) char2pos[t[i]].push_back(i);
for (char c : s) {
auto it = upper_bound(char2pos[c].begin(), char2pos[c].end(), pre);
if (it == char2pos[c].end()) return false;
pre = *it;
}
return true;
}
};
类似题目:
Number of Matching Subsequences
参考资料:
https://leetcode.com/problems/is-subsequence/
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Is Subsequence 是子序列的更多相关文章
- [LeetCode] Wiggle Subsequence 摆动子序列
		
A sequence of numbers is called a wiggle sequence if the differences between successive numbers stri ...
 - LeetCode 376. Wiggle Subsequence 摆动子序列
		
原题 A sequence of numbers is called a wiggle sequence if the differences between successive numbers s ...
 - [LeetCode] 891. Sum of Subsequence Widths 子序列宽度之和
		
Given an array of integers A, consider all non-empty subsequences of A. For any sequence S, let the ...
 - [leetcode]392. Is Subsequence 验证子序列
		
Given a string s and a string t, check if s is subsequence of t. You may assume that there is only l ...
 - [LeetCode] Increasing Subsequences 递增子序列
		
Given an integer array, your task is to find all the different possible increasing subsequences of t ...
 - 子序列 sub sequence问题,例:最长公共子序列,[LeetCode] Distinct Subsequences(求子序列个数)
		
引言 子序列和子字符串或者连续子集的不同之处在于,子序列不需要是原序列上连续的值. 对于子序列的题目,大多数需要用到DP的思想,因此,状态转移是关键. 这里摘录两个常见子序列问题及其解法. 例题1, ...
 - HDU 1159 Common Subsequence 公共子序列 DP 水题重温
		
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1159 Common Subsequence Time Limit: 2000/1000 MS (Jav ...
 - 392 Is Subsequence 判断子序列
		
给定字符串 s 和 t ,判断 s 是否为 t 的子序列.你可以认为 s 和 t 中仅包含英文小写字母.字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=10 ...
 - [LeetCode]152. 乘积最大子序列(DP)
		
题目 给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数). 示例 1: 输入: [2,3,-2,4] 输出: 6 解释: 子数组 [2,3] 有最大乘积 6. 示 ...
 
随机推荐
- 用eclipse开发项目时遇到的常见错误整理,和配套解决方案(1)
			
01. MyEclipse项目导入eclipse后,怎么发布不了? 今天导入了之前的一个MyEclipse项目,更改jdk后,发现发布不了.解决方案如下: 打开项目根目录,找到.settings文件夹 ...
 - ASP.NET Core 中文文档 第四章 MVC(2.2)模型验证
			
原文:Model Validation 作者:Rachel Appel 翻译:娄宇(Lyrics) 校对:孟帅洋(书缘) 在这篇文章中: 章节: 介绍模型验证 验证 Attribute 模型状态 处理 ...
 - Uri各个属性取值测试
			
asp.net代码: Uri h_uri = new Uri("http://hovertree.com/tiku/bjaf/3ntux9r9.htm?hewenqi#hewenqipl?d ...
 - C#遐想/瞎想
			
泛型约束更强大.比如支持有参构造函数.枚举.委托: void Foo<T>() where T : new(string, int), enum, delegate 空值判断符允许对属性/ ...
 - enumerate用法总结-Python 3
			
enumerate()说明 enumerate()是python的内置函数 enumerate在字典上是枚举.列举的意思 对于一个可迭代的(iterable)/可遍历的对象(如列表.字符串),enum ...
 - 【转】MVC、MVP与MVT
			
MVC是Model-View-Control的缩写,Model指的是数据层,View指的是UI层,Control指的是控制层,这三层之间彼此联系.View层的用户行为,触发Control层,Contr ...
 - [连载]《C#通讯(串口和网络)框架的设计与实现》- 14.序列号的设计,不重复的实现一机一码
			
目 录 第十四章 序列号的设计... 2 14.1 设计原则... 2 14.2 设计思想... 3 14.3 代码实现... 4 14. ...
 - python 学习笔记 -logging模块(日志)
			
模块级函数 logging.getLogger([name]):返回一个logger对象,如果没有指定名字将返回root loggerlogging.debug().logging.info().lo ...
 - About 静态代码块,普通代码块,同步代码块,构造代码块和构造函数的纳闷
			
构造函数用于给对象进行初始化,是给与之对应的对象进行初始化,它具有针对性,函数中的一种.特点:1:该函数的名称和所在类的名称相同.2:不需要定义返回值类型.3:该函数没有具体的返回值.记住:所有对象创 ...
 - 关于python字符串连接的操作
			
python字符串连接的N种方式 注:本文转自http://www.cnblogs.com/dream397/p/3925436.html 这是一篇不错的文章 故转 python中有很多字符串连接方式 ...