每日一题-判断子序列

判断子序列

int j = 0, i = 0;
	
while (i < m and j < n) {
    if (b[i] == a[j]) {
        j ++;
    }
    i ++;
}

cout << (j == n? "Yes" : "No");

description

for given sequence \(a\) and \(b\),decide whether \(a\) is a subsequence of \(b\).

two-pointers

for each \(a_i\), we greedily take the first occurence of it in \(b\). obviously, this strategy will mostly cover the elements in \(a\). To do this,
we use an \(O(n)\) algorithm called two pointers.
Pointer \(i\) and \(j\) point to \(a\) and \(b\) respectively. While \(i++\), if we find \(a_j == b_i\), then do \(j++\).

posted on 2022-11-10 08:56  Whosedream-0019  阅读(29)  评论(0)    收藏  举报

导航