problem no 37:(string problem):checks whether s1 is substring of s2 or not ,if yes then at what position?

 QUESTION:

 

Your task is to implement the function strstr. The function takes two strings as arguments (s2,s1) and  locates the occurrence of the string s1 in the string s2. The function returns and integer denoting the first occurrence of the string s1 in s2 (0 based indexing).

Example 1:

Input:
s1 = GeeksForGeeks, s2 = Fr
Output: -1
Explanation: Fr is not present in the
string GeeksForGeeks as substring.

 

Example 2:

Input:
s1 = GeeksForGeeks, s2 = For
Output: 5
Explanation: For is present as substring
in GeeksForGeeks from index 5 (0 based
indexing).
 

 ANSWER:

//this function checks whether s1 is substring of s2 or not ,if yes //then at what position.
 

int strstr(string s2, string s1)
{
   int M = s1.length();
    int N = s2.length();

    for (int i = 0; i <= N - M; i++) {
        int j;
 
        for (j = 0; j < M; j++)
            if (s2[i + j] != s1[j])
                break;
 
        if (j == M)
            return i;
    }
 
    return -1; 


Comments

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.