Substring C++ Example

Problem

You have the following function signature int Contains(char* s1, char* s2, int n1, int n2) where s1, s2 are two strings and n1, n2 are their respective lengths. The function should return 1 if the s1 contains s2 otherwise it returns 0. For example if s1 = abcdefg and s2 = acg then it should return 1 because all the characters in acg are found in s1 with the same order regardless of their position in s1. In other words the characters must be in s1 but not necessarily adjacent. Here is another example s1= abcdefg and s2 = acb, in this case the function should return false although all characters can be found in s1 but they do not maintain the sequence.

Solution

You need to loop in the second string and for each character you try to find a match in the first string. If you can not find a match any time then return false. Otherwise save the position of the match in the first string so that you start after it in the next iteration in order to keep track of the order. Once the two nested loops are finished without returning false then you can return true which means the second string is contained in the first string.

Code

Here is the code in C++

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *