LeetCode #392: Is Subsequence

Problem

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.

Solution

题意

给出两个字符串s和t,要求判断s是否是t的子串。

该题中对于子串的定义是:只要s中的字母以相同的顺序出现在t中,那么我们就说s是t的子串

示例见原题。

分析

从贪心算法的角度去看,解决这道题的思路是每判断一次都得到一个目前看起来最优的解,那么对于这道题来说,就要求每判断一次都能将问题的规模缩小。

所以解法就是。从s的第一个字母s[0]开始,从t[0]开始逐个匹配t中的字母,如果在t[i]处匹配,则继续匹配s[1],从t[i+1]开始。

重复这个过程,直到s中的字母全部完成匹配,则返回true;否则,到达t[t.size()-1]时仍未完成s的匹配,返回false

Code

//Runtime: 68ms
class Solution {
public:
    bool isSubsequence(string s, string t) {
        int sIndex = 0, tIndex = 0;             //index of string s and string t
        int sSize = s.size(), tSize = t.size();
        if (sSize == 0) return true;         //if s is empty string, s is every string's sub-string
        while (tIndex < tSize) {                //check all characters of string t
            if (s[sIndex] == t[tIndex]) {
                sIndex++;                       //if s[sIndex] and t[tIndex] are matched, then check the next character of s
                if (sIndex == sSize)            //which means all characters of s are matched
                    return true;
            }
            tIndex++;
        }
        return false;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,789评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,066评论 0 23
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,107评论 19 139
  • 翻飞的叶 不想坠落 也像我 念着归家 荏苒流光十载 却也忘了 当年 最初的面孔 是否 是否泪如雨下
    Gu岛鲸阅读 251评论 0 0
  • 我不是一个喜欢背书的人,也算不上一个喜欢看书的人,因为心里少有宁静,看着看着心就飞走了。 当偶尔看一本书,喜欢上了...
    Flora唐阅读 436评论 2 1