您的位置:首页 > 产品设计 > UI/UE

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