Open In App

Longest Substring containing C2, starting with C1 and ending with C3

Last Updated : 16 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string S. Find the longest Substring that starts with character C1, ends with character C3 and has at least one character C2 in between. Print “-1” if there exists no such substring.

Note: Uppercase and Lowercase letters are treated differently so ‘a’ and ‘A’ are not equivalent.

Examples:

Input: S = “aasdfdsafsdasf”, C1 = ‘d’, C2 = ‘s’, C3 = ‘d’
Output: 8 dfdsafsd
Explanation: “dfdsafsd” starts with ‘d’ and ends with ‘d’ and two ‘s’ in between.

Input: S = “GeeksForGeeks”, C1 = ‘G’, C2 = ‘e’, C3 = ‘k’
Output: 12 GeeksForGeek
Explanation: “GeeksForGeek” starts with ‘G’ and ends with ‘k’ and four ‘e’ in between.

Input: S = “Prophecy”, C1 = ‘p’, C2 = ‘p’, C3 = ‘t’
Output: -1
Explanation: No substring exists with starting character as ‘p’ and ending as ‘p’.

 

Approach: The problem can be solved using the below idea: 

Find the first occurrence of C1 and last occurrence of C3. If there is any C2 in between them, then this is the longest possible substring. Otherwise, no such substring is possible.

Follow the steps mentioned below to solve the problem:

  • Find the first occurrence of C1 in S (say i).
  • Start iterating from i to end of string:
    • Append the character to the longest substring.
    • If any character is the same as C2 increment count of C2.
    • If C3 is found and the count of C2 is not zero, update the longest substring.
  • If count is 0, return -1.
  • Otherwise, return the substring formed till the last occurrence of C3.

Below is the implementation of the above approach.

C++14




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the longest substring
string Solve(string& S, char& C1,
             char& C2, char& C3)
{
    int maxLen = 0, countB = 0,
        i, j, n = S.length();
 
    // First occurrence of C1
    for (i = 0; i < n; i++) {
        if (S[i] == C1) {
            j = i;
            break;
        }
    }
 
    // Finding the longest substring
    while (j++ < n) {
        if (S[j] == C2)
            countB++;
 
        if (countB > 0 && S[j] == C3)
            maxLen = max(maxLen, j - i + 1);
    }
 
    if (maxLen == 0)
        return "-1";
 
    return S.substr(i, maxLen);
}
 
// Driver code
int main()
{
    string S = "GeeksForGeeks";
    char C1 = 'G';
    char C2 = 'e';
    char C3 = 'k';
 
    string ans = Solve(S, C1, C2, C3);
 
    if (ans.compare("-1") == 0)
        cout << "-1";
    else
        cout << ans.length() << " "
             << ans;
    return 0;
}


Java




// Java code to implement the approach
public class GFG
{
   
    // Function to find the longest substring
    static String Solve(String S, char C1, char C2, char C3)
    {
        int maxLen = 0;
        int countB = 0;
        int i, j = 0;
        int n = S.length();
       
        // First occurrence of C1
        for (i = 0; i < n; i++) {
            if (S.charAt(i) == C1) {
                j = i;
                break;
            }
        }
       
        // Finding the longest substring
        while (++j < n) {
            if (S.charAt(j) == C2)
                countB++;
 
            if (countB > 0 && S.charAt(j) == C3)
                maxLen = Math.max(maxLen, j - i + 1);
        }
        if (maxLen == 0)
            return "-1";
        return S.substring(i, maxLen);
    }
   
    // Driver code
    public static void main(String[] args)
    {
        String S = "GeeksForGeeks";
        char C1 = 'G';
        char C2 = 'e';
        char C3 = 'k';
 
        String ans = Solve(S, C1, C2, C3);
        if (ans == "-1")
            System.out.println("-1");
        else
            System.out.println(ans.length() + " " + ans);
    }
}
 
//This code is contributed by phasing17


Python3




# Python 3 code to implement the approach
 
# Function to find the longest substring
def Solve(S,  C1,
          C2, C3):
 
    maxLen = 0
    countB = 0
    n = len(S)
 
    # First occurrence of C1
    for i in range(n):
        if (S[i] == C1):
            j = i
            break
 
    # Finding the longest substring
    while (j < n):
        if (S[j] == C2):
            countB += 1
 
        if (countB > 0 and S[j] == C3):
            maxLen = max(maxLen, j - i + 1)
        j += 1
 
    if (maxLen == 0):
        return "-1"
 
    return S[i: maxLen]
 
 
# Driver code
if __name__ == "__main__":
 
    S = "GeeksForGeeks"
    C1 = 'G'
    C2 = 'e'
    C3 = 'k'
 
    ans = Solve(S, C1, C2, C3)
 
    if (ans == "-1"):
        print("-1")
    else:
        print(len(ans), ans)
 
        # This code is contributed by ukasp.


C#




// C# code to implement the approach
using System;
class GeeksForGeeks {
 
    // Function to find the longest substring
    static string Solve(string S, char C1, char C2, char C3)
    {
        int maxLen = 0, countB = 0, i = 0, j = 0,
            n = S.Length;
 
        // First occurrence of C1
        for (i = 0; i < n; i++) {
            if (S[i] == C1) {
                j = i;
                break;
            }
        }
 
        // Finding the longest substring
        while (j < n) {
            if (S[j] == C2)
                countB++;
 
            if (countB > 0 && S[j] == C3)
                maxLen = Math.Max(maxLen, j - i + 1);
 
            j++;
        }
 
        if (maxLen == 0)
            return "-1";
 
        return S.Substring(i, maxLen);
    }
 
    // Driver code
    public static void Main()
    {
        string S = "GeeksForGeeks";
        char C1 = 'G';
        char C2 = 'e';
        char C3 = 'k';
 
        string ans = Solve(S, C1, C2, C3);
 
        if (ans == "-1")
            Console.Write("-1");
        else
            Console.Write(ans.Length + " " + ans);
    }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
// JavaScript code for the above approach
 
// Function to find the longest substring
function Solve(S, C1,
              C2, C3)
{
    let maxLen = 0, countB = 0,
        i, j, n = S.length;
 
    // First occurrence of C1
    for (i = 0; i < n; i++) {
        if (S[i] == C1) {
            j = i;
            break;
        }
    }
 
    // Finding the longest substring
    while (j++ < n) {
        if (S[j] == C2)
            countB++;
 
        if (countB > 0 && S[j] == C3)
            maxLen = Math.max(maxLen, j - i + 1);
    }
 
    if (maxLen == 0)
        return "-1";
 
    return S.slice(i, maxLen);
}
 
// Driver code
 
    let S = "GeeksForGeeks";
    let C1 = 'G';
    let C2 = 'e';
    let C3 = 'k';
 
    let ans = Solve(S, C1, C2, C3);
 
    if (ans=="-1")
        document.write( "-1");
    else
        document.write(ans.length + " " + ans)
     
      // This code is contributed by Potta Lokesh
 
    </script>


Output

12 GeeksForGeek

Time Complexity: O(N), where N is the length of the string
Auxiliary Space: O(1) , since there is no extra array or data structure used, it takes constant space.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads