Subsequence - 392. Is Subsequence
- 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 sis 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中出现的位置。
代码:
java:
class Solution {
public boolean isSubsequence(String s, String t) {
if (s == null || s.length() == 0) return true;
if (t == null || t.length() == 0) return false;
/* int index = 0;
for (int i = 0; i < t.length(); i++) {
if (s.charAt(index) == t.charAt(i)) index++;
if (index == s.length()) return true;
}
return false;*/
int prev = -1;
for (int i = 0; i < s.length(); i++) {
int index = t.indexOf(s.charAt(i), prev+1);
if (index < 0) {
return false;
}
prev = index;
}
return true;
}
}
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- PHP示例演示发送邮件给某个邮箱
- PHP设计模式之观察者模式定义与用法分析
- PHP实现数组向任意位置插入,删除,替换数据操作示例
- 实例讲解Python 迭代器与生成器
- opencv 图像轮廓的实现示例
- 基于python实现可视化生成二维码工具
- Python word实现读取及导出代码解析
- Python项目跨域问题解决方案
- keras的load_model实现加载含有参数的自定义模型
- opencv 图像加法与图像融合的实现代码
- PHP图像处理技术实例总结【绘图、水印、验证码、图像压缩】
- python如何实现读取并显示图片(不需要图形界面)
- PHP文件操作实例总结【文件上传、下载、分页】
- Django中Aggregation聚合的基本使用方法
- ThinkPHP3.2.3框架实现执行原生SQL语句的方法示例