C/C++ 题目:给定字符串s1和s2,判断s1是否是s2的子序列

判断子序列一个字符串是否是另一个字符串的子序列

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


示例 1:
    输入:s1 = "ac", s2 = "ahbgdc"
    输出:true

示例 2:
    输入:s = "ax", t = "acdgbgdc"
    输出:false

解析:

         按照s2的字符串顺序去找,如果s1是s2的子序列,那么一定能找到对应的s1中的所有字符,

         如果遍历了s2,而s1中还有剩余的长度没有找到,那么说明s1不是s2的子序列。

示例源码:

// Len_findChild.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <string>
using namespace std;
bool JudgeChildStr(string s, string t) 
{
	int count = s.size() - 1;
	for (int i = t.size() - 1; i >= 0 && count >= 0; i--)
	{
		if (t[i] == s[count])
		{
			count--;
		}
	}

	if (count < 0)
	{
		return true;
	}
	return false;
}

int main()
{
	string s1 = "ac";
	string s2 = "ahbgdc";
	bool bResult = JudgeChildStr(s1, s2);
	printf("\n\ts1 = %s \n\ts2 = %s \n\tresult: %s\n", s1.c_str(), s2.c_str(), (bResult==0)?("false"):("true"));

	s1 = "ax";
	s2 = "acdgbgdc";
	bResult = JudgeChildStr(s1, s2);
	printf("\n\ts1 = %s \n\ts2 = %s \n\tresult: %s\n", s1.c_str(), s2.c_str(), (bResult == 0) ? ("false") : ("true"));

}

执行结果:


 

  • 8
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WendyWJGu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值