跳转至

392.判断子序列 (Easy)*

题目描述*

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

你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。

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

示例*

s = "abc", t = "ahbgdc"

返回 true.

s = "axc", t = "ahbgdc"

返回 false.

后续挑战*

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

代码*

原题比较简单,只要逐个比较即可。后续挑战输入量大,先把 t 字符串 26 个字母的位置分存,逐个字符判断 s 的字符顺序是否再 t 内。

class Solution {
public:
    bool isSubsequence(string s, string t) {
        if(s.length() == 0) {
            return true;
        }
        int j = 0;
        int len = t.length();
        for(int i = 0; i < len; i++) {
            if(t[i] == s[j]) {
                j++;
            }
            if(j == s.length()) {
                return true;
            }
        }
        return false;
    }
};
class Solution {
public:
    bool isSubsequence(string s, string t) {
        if(s.length() == 0) {
            return true;
        }
        vector<vector<int>> res(26);
        int pos = -1;
        for(int i = 0; i < t.length(); i++) {
            res[t[i] - 'a'].push_back(i);
        }
        for(int i = 0; i < s.length(); i++) {
            int curLetter = s[i] - 'a';
            int l = 0, r = res[curLetter].size() - 1;
            while(l < r) {
                int mid = l + (r - l) / 2;
                if(res[curLetter][mid] > pos) {
                    r = mid;
                }else {
                    l = mid + 1;
                }
            }
            if(r < l || res[curLetter][l] < pos) {
                return false;
            }
            pos = res[curLetter][l];
        }
        return true;
    }
};

最后更新: July 23, 2022