📌  相关文章
📜  检查字符串是否包含两个不重叠的子字符串“geek”和“keeg”

📅  最后修改于: 2022-05-13 01:57:08.607000             🧑  作者: Mango

检查字符串是否包含两个不重叠的子字符串“geek”和“keeg”

给定一个字符串str ,任务是检查该字符串是否包含两个不重叠的子字符串s1 = “geek”s2 = “keeg” ,使得s2s1结束后开始。
例子:

方法:检查给定字符串中的子字符串“geek”是否出现在“keeg”之前。当我们使用预定义的函数strstr 来查找给定字符串中子字符串的出现时,这个问题就更简单了。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function that returns true
// if s contains two non overlapping
// sub strings "geek" and "keeg"
bool isValid(char s[])
{
    char* p;
 
    // If "geek" and "keeg" are both present
    // in s without over-lapping and "keeg"
    // starts after "geek" ends
    if ((p = strstr(s, "geek")) && (strstr(p + 4, "keeg")))
        return true;
 
    return false;
}
 
// Driver code
int main()
{
    char s[] = "geekeekeeg";
 
    if (isValid(s))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
 
// Function that returns true
// if s contains two non overlapping
// sub Strings "geek" and "keeg"
static boolean isValid(String s)
{
    // If "geek" and "keeg" are both present
    // in s without over-lapping and "keeg"
    // starts after "geek" ends
    if ((s.indexOf( "geek")!=-1) &&
        (s.indexOf( "keeg",s.indexOf( "geek") + 4)!=-1))
        return true;
 
    return false;
}
 
// Driver code
public static void main(String args[])
{
    String s = "geekeekeeg";
 
    if (isValid(s))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by Arnab Kundu


Python3
# Python 3 implementation of the approach
 
# Function that returns true
# if s contains two non overlapping
# sub strings "geek" and "keeg"
def isValid(s):
    p=""
 
    # If "geek" and "keeg" are both present
    # in s without over-lapping and "keeg"
    # starts after "geek" ends
    p=s.find("geek")
    if (s.find("keeg",p+4)):
        return True
 
    return False
 
# Driver code
if __name__ == "__main__":
    s = "geekeekeeg"
 
    if (isValid(s)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by ChitraNayal


C#
// C# implementation of the approach
 
using System;
 
class GFG
{
 
// Function that returns true
// if s contains two non overlapping
// sub Strings "geek" and "keeg"
static bool isValid(string s)
{
    // If "geek" and "keeg" are both present
    // in s without over-lapping and "keeg"
    // starts after "geek" ends
    if ((s.IndexOf( "geek")!=-1) &&
        (s.IndexOf( "keeg",s.IndexOf( "geek") + 4)!=-1))
        return true;
 
    return false;
}
 
// Driver code
public static void Main()
{
    string s = "geekeekeeg";
 
    if (isValid(s))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by AnkitRai01


Javascript


输出:
Yes