LeetCode 392. Is Subsequence

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).

题目内容:
给定字符串s和t,判断字符串s是否字符串t的一个子序列。
这里的子序列跟子字符串不一样,子字符串在原字符串中是连续出现的,而这里的子序列只要是与子序列的字符出现顺序一样就可以了,例如”ace”是”abcde”的一个子序列,因为”abcde”中按照a->c->e的顺序出现了”a”、”c”和”e”。

解题思路:
要判断s是否t的一个子序列,我的想法是从t中依次查找s中的每个字符,也就是先从t中查找s的第一个字符,假如是在t[i]的位置,如果找到了再从i+1的位置往后找s的第二个字符,以此类推,如果在遍历完t之前,s的所有字符都被找到了,说明s是t的一个子序列,否则不是。
在程序中我用的是string::iterator来对字符串s和t进行遍历,因为程序中获取字符串的每个字符都是按照从左到右的顺序的,所以使用迭代器的自加可以方便的获取到字符,而且效率比下标索引要快。程序中有1个while循环,用作遍历字符串t,如果循环到的字符与s的第一个字符相同,则s的迭代器指向下一个字符的位置,这样一直循环下去,直到s的迭代器指向了s的结尾,表明s是t的子序列,或者s的迭代器还没到s的结尾,但是字符串t的字符已经遍历完了,说明s不是t的子序列。

代码:

#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    bool isSubsequence(string s, string t) {
        bool flag = false;
        if(s.length() == 0) {
            return true;
        }
        if(s.length() > t.length() || t.length() == 0){
            return flag;
        }
        string::iterator s_it = s.begin();
        string::iterator t_it = t.begin();
        while(t_it != t.end()) {
            if(*s_it == *t_it) {
                s_it++;
                if(s_it == s.end()) {
                    flag = true;
                    break;
                }
            }
            t_it++;
        }
        return flag;
    }
};

int main(int argc, const char * argv[]) {
    Solution sln;
    cout << sln.isSubsequence("axc", "ahbgdc") << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值