Sorapalli Venkatesh
Sorapalli Venkatesh

Reputation: 59

Sub-sequence of characters

Here have to find the sebsequence of characters in 2 strings.. 1st string is "stackoverflow" 2nd string is user input which contains may or may not the string-1 as a sub-sequence of characters.

i.e.,stdachfdkoverrfloow it contains string1 data as a subsequence characters then output should display YES

i.e., "stackoverway" it does not contains string1 data as a subsequence characters then output should display NO

Here is my code..

#include <bits/stdc++.h>
#include<iostream>
#include<cstring>
using namespace std;

bool SubSeq(char str1[], char str2[], int m, int n)
{
if (m == 0) 
    return true;
if (n == 0) 
    return false;

if (str1[m-1] == str2[n-1])
    return SubSeq(str1, str2, m-1, n-1);

return SubSeq(str1, str2, m, n-1);
}

int main()
{
int q;
cin >> q;

for(int a0 = 0; a0 < q; a0++)
{
    char str1[] = "stackoverflow";
    int m = strlen(str1);
    char str2[] = "";
    cin >> str2; 
    int n = strlen(str2);
    SubSeq(str1, str2, m, n) ? cout << "YES\n" : cout << "NO\n";
}
return 0;
}

In the above code i am getting the output as follows..

YES
NO
NO
NO
NO
NO
NO
NO .......(truncated)

I don't know why this NO occurs so many times..Can anyone tell me where i have done a wrong step..

Thanks in advance

Venkatesh

Upvotes: 1

Views: 299

Answers (1)

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

You declare str2 as empty and then try to store the input into it.Use std::string

char str1[] = "stackoverflow";
int m = strlen(str1);
char str2[] = ""; //Notice the size of str2
cin >> str2; 

You can also follow the below approach

Keep on searching for the first character of to_be_searched in search_here.When found say at i position, continue from i+1 position for the second character of to_be_searched and son on.

bool check(string to_be_Searched,string search_here)
{
    for(int i=0,j=0;j<to_be_searched.length() && i<search_here.length();i++)
    {
       if(to_be_Searched[j]==search_here[i])
          j++;
    }
    return j==to_be_searched.length();
 }

Upvotes: 1

Related Questions