392. Is Subsequence | LeetCode Dynamic Programming
2017-05-22 02:47
417 查看
Description
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.
Difficulty: Medium
Thinking
本题要求判断短字符串是不是长字符串的子序列。方法很简单,从s和t的首位开始遍历两字符串进行比较,当s中的字符与t中字符相同时,s与t字符数组的下标都加1;不相同时,s下标固定,t的坐标加1,直到相同。当t字符串的遍历坐标大于t的长度,而s串的遍历下表仍小于s长度时,说明s不是t的子序列,函数返回false。否则返回true。需要注意的是,当s为空串时,s一定是t的子序列,函数返回true。Solution
class Solution { public: bool isSubsequence(string s, string t) { int slen = s.size(); int tlen = t.size(); int j = 0, i = 0; if(slen == 0) return true; for(; i < slen; i++){ while(t[j] != s[i] && j < tlen) j++; if(j >= tlen) return false; j++; } return true; } };
相关文章推荐
- [Leetcode]-Basic Dynamic Programming(1)
- LeetCode /Dynamic Programming/Climbing Stairs
- 486. Predict the Winner Add to List | Leetcode Dynamic Programming
- 377. Combination Sum IV | Leetcode Dynamic Programming
- LeetCode/Dynamic Programming/Unique Paths
- dynamic-programming-python-leetcode(动态规划)
- leetcode最优解整理(dfs/String/Binary Search/Two pointers/Math/Dynamic programming)
- leetcode Ch2-Dynamic Programming II
- LeetCode Summary Dynamic Programming
- Leetcode - Tree /Dynamic Programming- Unique Binary Search
- LeetCode - Fibonacci Sequence/Dynamic Programming - Climbing Stairs
- 2016 UESTC Training for Dynamic Programming L - 柱爷抢银行MkⅣ dp 线段树优化
- [4_1_nuggets] Dynamic Programming or Number Theory
- implement the maximum subarray using dynamic programming
- linux c dynamic library programming
- HDU - 4972 A simple dynamic programming problem (14多校)思维
- 2014 UESTC Training for Dynamic Programming F
- HDU 4972 A simple dynamic programming problem
- UESTC_导弹拦截 2015 UESTC Training for Dynamic Programming<Problem N>
- 【杂题】 HDOJ 4972 A simple dynamic programming problem