[DP]392. Is Subsequence
来源:互联网 发布:mac版qq文件夹在哪里 编辑:程序博客网 时间:2024/06/03 18:15
题目:
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 andt. t is potentially a very long (length ~= 500,000) string, ands 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
.
题目分析:
1、题目要求根据传入的两个字符串s和t,判断s是否为t的子序列;
2、该题算法的构思比较简单。按从头到尾的顺序,先取出s的第一个字符,从t的头部开始依次向尾检验直至找到匹配项,此后再从s中取出第二个字符从t中找到匹配项的后一项开始继续往后检验,直至s取完或者t取完。
3、代码设计方面,设置两个参数int sL和int tL表示当前取出元素的下标,当找到匹配项后,sL和tL都++。设置新函数f引入tL和sL两个新参数,利用递归的方法来实现代码的简化。由于每个字符只检验一次,那么函数的时间复杂度为O(len(s)+len(n))。
4、递归的终止条件分为两个:sL == s.size(),即表示sL已经到s的末尾,s已检验完毕,返回true;tL = t.size(),即tL已到t末尾,t已检验完,返回false。
代码:
bool f(string &s, int sL, string &t, int tL){ if(sL == s.size()) return true; while(s[sL] != t[tL] && tL < t.size()) tL++; if(tL == t.size()) return false; sL++; tL++; return f(s, sL, t, tL);}class Solution {public: bool isSubsequence(string s, string t){ return f(s, 0, t, 0); }};
- [DP]392. Is Subsequence
- 392. Is Subsequence
- 392.[LeetCode] Is Subsequence
- 392. Is Subsequence
- 392. Is Subsequence
- LeetCode 392. Is Subsequence
- 392. Is Subsequence
- 392. Is Subsequence
- [LeetCode] 392. Is Subsequence
- 【leetcode】392. Is Subsequence
- 【LeetCode】392. Is Subsequence
- 【LeetCode】392. Is Subsequence
- 392. Is Subsequence
- 392. Is Subsequence
- Leetcode 392. Is Subsequence
- 392. Is Subsequence
- 392. Is Subsequence
- leetcode 392. Is Subsequence
- This
- 开源搜索平台选型:ElasticSearch、Solr
- LeetCode 53. Maximum Subarray
- Servlet之生命周期
- 原型和原型链继承
- [DP]392. Is Subsequence
- Java学习路线之基础篇
- NDK学习笔记(1)——第一个jni程序
- Grunt 新手一日入门
- [FFT] [HDU4609] 3-idiots
- 游行者-达瓦更扎
- ubuntu 启动SS
- 深度学习资料
- 戒撸总结一