LeetCode OJ-392.Is Subsequence

来源:互联网 发布:摄像机ntp端口号 编辑:程序博客网 时间:2024/06/06 02:35

LeetCode OJ-392.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.

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.

Subscribe to see which companies asked this question.

题目理解

​ 给定字符串s和t,判断s是否是t的子序列。这里的子序列含义是,s中各字符均在t中存在,且出现顺序一致。这里可以使用两个索引,一个i,一个j,i作为t的索引,j作为s的索引,以t为主,进行循环,当发现s[j] == t[i]时,对j进行自增。这样就保证了顺序,不用再做其他操作来保证顺序。如果s是t的子序列,那最终j应该是等于s的长度的。具体代码如下:

Code

bool is_subsequence(const string &s, const string &t){    int len1 = (int) s.length();    int len2 = (int) t.length();    if (len1 == 0) {  // 零长的s必定是任何一个字符串的子序列        return true;    }    int i, j;    for (i = 0, j = 0; i < len2 && j < len1; ++i) {        if (s[j] == t[i]) {            ++j;        }        if (j == len1) {  // s中的所有字符均已在t中按序找到            break;        }    }    if (i < len2 && j == len1) {        return true;    }    return false;}
0 0