Leetcode 392. 判断子序列 贪心

地址  https://leetcode-cn.com/problems/is-subsequence/

给定字符串 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.

后续挑战 :

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

解答

逐个比较字符串s和字符串t 由于是子序列不是连续子字符串,那么匹配的索引尽量靠前。

代码如下

class Solution {
public:
    bool isSubsequence(string s, string t) {
        if(s.empty() && t.empty()) return true;
        int k = 0;
        for(int i = 0;i < t.size();i++){
            if(s[k] == t[i]){
                k++;
            }
            if(k == s.size())
                return true;
        }
        return false;
    }
};

后继挑战 使用26长度的数组 记录各个字母在字符串t中的出现索引

在逐个比对字符串s的字母时候 使用二分查找 尽量找出可能靠前的索引。

class Solution {
public:
    
    vector<int> le[26];

int SearchSmallestIdx(int idx, int limit)
{
    int l = 0; int r = le[idx].size();

    while (l < r) {
        int mid = (l + r) >> 1;
        if (le[idx][mid] >= limit)  r = mid;
        else l = mid + 1;
    }
    if (l >= le[idx].size()) return -1;
    return   le[idx][l];
}


bool isSubsequence(string s, string t) {
    for (int i = 0; i < t.size(); i++) {
        int idx = t[i] - 'a';
        le[idx].push_back(i);
    }
    int findidx = -1;
    for (int i = 0; i < s.size(); i++) {
        int idx = s[i] - 'a';
        findidx = SearchSmallestIdx(idx, findidx + 1);
        if (findidx == -1) return false;
    }

    return true;
}
    
};
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/12823550.html