Check if a string contains two non overlapping sub-strings “geek” and “keeg”
Last Updated :
22 Dec, 2022
Given a string str, the task is to check whether the string contains two non-overlapping sub-strings s1 = “geek” and s2 = “keeg” such that s2 starts after s1 ends.
Examples:
Input: str = “geekeekeeg”
Output: Yes
“geek” and “keeg” both are present in the
given string without overlapping.
Input: str = “geekeeg”
Output: No
“geek” and “keeg” both are present but they overlap.
Approach: Check if the sub-string “geek” occurs before “keeg” in the given string. This problem is simpler when we use a predefined function strstr in order to find the occurrence of a sub-string in the given string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isValid( char s[])
{
char * p;
if ((p = strstr (s, "geek" )) && ( strstr (p + 4, "keeg" )))
return true ;
return false ;
}
int main()
{
char s[] = "geekeekeeg" ;
if (isValid(s))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG
{
static boolean isValid(String s)
{
if ((s.indexOf( "geek" )!=- 1 ) &&
(s.indexOf( "keeg" ,s.indexOf( "geek" ) + 4 )!=- 1 ))
return true ;
return false ;
}
public static void main(String args[])
{
String s = "geekeekeeg" ;
if (isValid(s))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isValid(s):
p = ""
p = s.find( "geek" )
if (s.find( "keeg" ,p + 4 )):
return True
return False
if __name__ = = "__main__" :
s = "geekeekeeg"
if (isValid(s)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool isValid( string s)
{
if ((s.IndexOf( "geek" )!=-1) &&
(s.IndexOf( "keeg" ,s.IndexOf( "geek" ) + 4)!=-1))
return true ;
return false ;
}
public static void Main()
{
string s = "geekeekeeg" ;
if (isValid(s))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function isValid(s)
{
if ((s.indexOf( "geek" ) != -1) &&
(s.indexOf( "keeg" , s.indexOf( "geek" ) + 4) != -1))
return true ;
return false ;
}
var s = "geekeekeeg" ;
if (isValid(s))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n), for using indexof() function which takes a linear time.
Auxiliary Space: O(n), where n is the length of the given string.
Share your thoughts in the comments
Please Login to comment...