392. Is Subsequence
2016-09-06 21:02
369 查看
题目:Is Subsequence
原题链接:https://leetcode.com/problems/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.
给出一个字符串 s 和 t ,判断 s 是不是 t 的子串。
题目保证 s 和 t 中只含有小写字母,并且 t 的长度大概在500,000, s 的长度不超过100.
注:子串的定义要求 s 字符串的字符在 t 中的相对位置不能变,所以“ace”是“abcde”的子串而“aec”不是。
例:
s = “abc”, t = “ahbgdc” 则 s 是 t 的子串
s = “axc”, t = “ahbgdc” 则 s 不是 t 的子串
由子串的定义可以发现,假设 a 和 b 是 s 中的两个字符,且 a 的下标在 b 之前,那么,如果 s 是 t 的子串的话, a 和 b 在 t 中的下标也一定是 a 在前 b 在后。
我们可以从尾到头扫描字符串,当扫描到 s 中某个字符 a 在 t 中存在的时候,如果是子串,那么 t 继续往前扫描的话一定会依次遇到a的前一个字符,前前字符,前前前字符。。。这样在 t 扫描完之前如果能够把 s 中的字符都扫描到,那么 s 就是 t 的子串。
代码如下:
class Solution { public: bool isSubsequence(string s, string t) { int i = s.length() - 1, j = t.length() - 1; while(i >= 0 && j >= 0) { if(t[j] == s[i]) i--; j--; } if(i == -1) return true; else return false; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解