The Subsequence Algorithm for Two Strings – How to Check i

  • 时间:2020-09-21 09:15:21
  • 分类:网络文摘
  • 阅读:98 次

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?

The Two Pointer String Subsequence Algorithm

If source string s is larger than source string t, s must not be a subsequence of t. Otherwise, we can have two pointers i and j, pointing initialially to the begining of the two strings s and t respectively. If at any time, s[i] == t[j], we move both pointers to next position, otherwise, we need to increment j, until either of the pointer is beyond the end of the source string.

If ever i reaches the end, it indicates that source string s is a subsequence of string b. The time complexity of the two pointer algorithm regarding this problem is O(Max(N, M)) where N and M are the sizes of the string s and t respectively.

The algorithm uses a constant O(1) space.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
    bool isSubsequence(string s, string t) {
        if (s.size() > t.size()) return false;
        int i = 0, j = 0;
        int n1 = s.size(), n2 = t.size();
        while ((i < n1) && (j < n2)) {
            if (s[i] == t[j]) {
                i ++;
                j ++;
            } else {
                j ++;
            }
        }
        return i == n1;
    }
};
class Solution {
public:
    bool isSubsequence(string s, string t) {
        if (s.size() > t.size()) return false;
        int i = 0, j = 0;
        int n1 = s.size(), n2 = t.size();
        while ((i < n1) && (j < n2)) {
            if (s[i] == t[j]) {
                i ++;
                j ++;
            } else {
                j ++;
            }
        }
        return i == n1;
    }
};

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
29957四舍五入到百位、千位、万位是多少?  已知被除数,除数,商与余数的和是235,已知商是27,余数是6,求除数。  图中几条直线、几条射线、几条线段?  滞尘是什么意思?  冬冬是2008年2月29日出生的,到2016年2月29日他一共过了几个生日?  饮料架上放有大、中、小三种包装的饮料  有一架天平和一个50克的砝码,如果要得到150克糖果  看似容易-六年级易错题集锦  从前往后数小明排在第7位  三年级上册第九单元思考题:学校举行乒乓球比赛 
评论列表
添加评论