Maximum Length Prefix

QUESTION

You are given two string S1 and S2. Find the maximal length of some prefix of the string S1 which occurs in strings S2 as subsequence.\n\nInput\nThe first line contains string S1. The second line contains string S2. Both strings consist of lowecase Latin letters.\n\nOutput\nOutput one integer – answer to the question.\n\nConstraints\n1 <= length of S1, S2 <= 10^6.

ANSWER

#include<bits/stdc++.h>
using namespace std;
string st1,st2;
int ptr;
int main(){
ios_base::sync_with_stdio(0);
cin>>st1>>st2;
ptr=0;
for (int i=0;i<st2.size();i++){
    if (ptr==st1.size())
        break;

    if (st2[i]==st1[ptr])
        ++ptr;
}
cout<<ptr<<endl;
return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.