392. 判断子序列

55 阅读1分钟

392. 判断子序列

简单

相关标签

premium lock icon相关企业

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

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

进阶:

如果有大量输入的 S,称作 S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?

致谢:

特别感谢 ****@pbrother 添加此问题并且创建所有测试用例。

 

示例 1:

输入: s = "abc", t = "ahbgdc"
输出: true

示例 2:

输入: s = "axc", t = "ahbgdc"
输出: false

 

提示:

  • 0 <= s.length <= 100
  • 0 <= t.length <= 10^4
  • 两个字符串都只由小写字符组成。

题解: 简单的双指针,各自扫描一个字符串即可。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char sonstr[100] = {'\0'};
    char tstr[10000] = {'\0'};
    gets(sonstr);
    gets(tstr);

    int i = 0, j = 0;
    int ssize, tsize;
    ssize = strlen(sonstr);
    tsize = strlen(tstr);
    while (i <= ssize - 1 && j <= tsize - 1)
    {
        if (sonstr[i] == tstr[j])
        {
            i ++;
            j ++;
        }
        else j ++;
    }
    if (i == ssize)
    {
        printf("true");
    }
    else printf("false");

    return 0;
}