Leetcode实战: 392. 判断子序列

题目

给定字符串 s 和 t ,判断 s 是否为 t 的子序列。

你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。

字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。

示例1

s = "abc", t = "ahbgdc"
返回 true.

示例2

s = "axc", t = "ahbgdc"

返回 false.

算法实现:双指针

class Solution {
public:
    bool isSubsequence(string s, string t) {
        if (s=="") return 1;
        int j(0), length(s.size());
        for (int i = 0; i < t.size(); i++) {
            if (t[i] == s[j]) j++;
                if (j == length) return 1;
        }
        return 0;
    }
};

结果

在这里插入图片描述

发布了154 篇原创文章 · 获赞 52 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44315987/article/details/105114040