Is Subsequence

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

Example 1:

s = “abc”, t = “ahbgdc”
Return true.

Example 2:

s = “axc”, t = “ahbgdc”
Return false.

Follow up:
If there are lots of incoming S, say S1, S2, … , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?

Difficulty:Medium

TIME:20MIN

解法一

一开始想这道题怎么这么简单,怎么可能是中等难度,因为如果是单纯判断是否是某个字符串的子串的话,只需要遍历一般就行了。

bool isSubsequence(string s, string t) {
    int k = 0;
    for(size_t i = 0; i < t.size(); i++) {
        if(t[i] == s[k])
            k++;
    }
    return k == s.size();
}

代码的时间复杂度为 O(n) ,其中 n=t.size()

解法二

但其实这道题真正的难点在于Follow up中所问题内容,也就是说不是单独的字符串s,而是多个字符串s,这样的话如果采用上面的解法,如果有k个字符串s,则时间复杂度为 O(kn) ,我们知道n是很大的,所以当然不能这样解。

而这道题的思路在于预处理,就是对字符串t做一个预处理,我这里采用的是将t中字符与它的位置做一个映射,也就是说给定某个字符,我能立刻确定这个字符在t中的所有位置,而且这些位置是增序的,因此可以用二分来查找。我只需要一直寻找最小的比当前位置大的位置作为下一个字符的位置就行了。

void isSubsequence(vector<string> s, string t) {
    map<int,vector<int>> m;
    vector<bool> result; //保存每个字符串的判断结果
    for(size_t i = 0; i < t.size(); i++) {
        m[t[i]].push_back(i);  //将字符映射到位置数组
    }
    int last;
    for(size_t i = 0; i < s.size(); i++) {
        last = -1;
        size_t j = 0;
        for(; j < s[i].size(); j++) {
            //找到最小的比上一个位置大的位置作为当前字符的位置
            auto it = upper_bound(m[s[i][j]].begin(), m[s[i][j]].end(), last);
            if(it != m[s[i][j]].end())
                last = *it;
            else 
                break;
        }
        if(j == s[i].size())
            result.push_back(true);
        else
            result.push_back(false);
    }
    return;
}

这样的话,总的时间复杂度就变成了 O(n+100klogn) ,因此约为 O(n) ,也就是说不管处理多少个字符串,时间复杂度都不会有特别大的变化。

总结
对字符串进行预处理有时候是必要的,特别是这种字符串长度差距十分大的情况,字符串匹配的自动机算法就是对字符串进行了预处理,因此,时间复杂度可以稳定在 O(n) ,时间复杂度和KMP算法相当。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值