Largest substring of str2 which is a prefix of str1
Given two string str1 and str2, the task is to find the longest prefix of str1 which is present as a substring of the string str2. Print the prefix if possible else print -1.
Examples:
Input: str1 = “geeksfor”, str2 = “forgeeks”
Output: geeks
All the prefixes of str1 which are present in str2
are “g”, “ge”, “gee”, “geek” and “geeks”.
Input: str1 = “abc”, str2 = “def”
Output: -1
Approach: Check whether str1 is present as a substring in str2. If yes then str1 is the required string else remove the last character from str1 and repeat these steps until either the string str1 becomes empty or the required string is found.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
string findPrefix(string str1, string str2)
{
int pos = -1;
while (!str1.empty()) {
if (str2.find(str1) == string::npos)
str1.pop_back();
else {
pos = str2.find(str1);
break ;
}
}
if (pos == -1)
return "-1" ;
return str1;
}
int main()
{
string str1 = "geeksfor" ;
string str2 = "forgeeks" ;
cout << findPrefix(str1, str2);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static String findPrefix(String str1,
String str2)
{
boolean pos = false ;
while (str1.length() > 0 )
{
if (!str2.contains(str1))
str1 = str1.substring( 0 , str1.length() - 1 );
else
{
pos = str2.contains(str1);
break ;
}
}
if (pos == false )
return "-1" ;
return str1;
}
public static void main(String[] args)
{
String str1 = "geeksfor" ;
String str2 = "forgeeks" ;
System.out.println(findPrefix(str1, str2));
}
}
|
Python3
import operator
def findPrefix(str1, str2):
pos = False ;
while ( len (str1) ! = 0 ):
if operator.contains(str2, str1) ! = True :
str1 = str1[ 0 : len (str1) - 1 ];
else :
pos = operator.contains(str2, str1);
break ;
if (pos = = False ):
return "-1" ;
return str1;
if __name__ = = '__main__' :
str1 = "geeksfor" ;
str2 = "forgeeks" ;
print (findPrefix(str1, str2));
|
C#
using System;
class GFG
{
static String findPrefix(String str1,
String str2)
{
bool pos = false ;
while (str1.Length > 0)
{
if (!str2.Contains(str1))
str1 = str1.Substring(0, str1.Length - 1);
else
{
pos = str2.Contains(str1);
break ;
}
}
if (pos == false )
return "-1" ;
return str1;
}
public static void Main(String[] args)
{
String str1 = "geeksfor" ;
String str2 = "forgeeks" ;
Console.WriteLine(findPrefix(str1, str2));
}
}
|
Javascript
<script>
function findPrefix(str1, str2)
{
var pos = -1;
while (str1.length!=0) {
if (!str2.includes(str1))
str1 = str1.substring(0,str1.length-1)
else {
pos = str2.includes(str1);
break ;
}
}
if (pos == -1)
return "-1" ;
return str1;
}
var str1 = "geeksfor" ;
var str2 = "forgeeks" ;
document.write( findPrefix(str1, str2));
</script>
|
Time Complexity: O(N * M) where N, M are the lengths of given strings.
Last Updated :
08 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...