LeetCode 392. Is Subsequence

来源:互联网 发布:视频相片制作软件 编辑:程序博客网 时间:2024/06/16 19:09

题目:
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?

思路: 简单的方法就是遍历s串和t串 ,如果串s和串t当前的字符相等,两个的索引都加1;否则 只是t串的索引加1。具体思路见注释 ~ 很简单

代码:

class Solution {public:    bool isSubsequence(string s, string t) {        int lens=s.length();//分别求两个字符串的长度        int lent=t.length();        int i,j;        for(i=0,j=0;i<lens&&j<lent;){//遍历            if(s[i]==t[j]){//如果串s和串t当前的字符相等,两个的索引都加1                ++i;                ++j;            }            else{//否则 只是t串的索引加1                ++j;            }        }        if(i==lens){//如果i最终等于lens也就是s串中的字符都在按顺序在t串中找到,返回true            return true;        }        else{//否则 返回false            return false;        }    }};

结果: 73ms