Home  >  Article  >  Backend Development  >  C++ code to find two substrings with a minimum substring

C++ code to find two substrings with a minimum substring

WBOY
WBOYforward
2023-09-06 14:41:14894browse

C++ code to find two substrings with a minimum substring

Suppose we have a lowercase string S, which contains n characters. We need to find two non-empty Substrings P and Q such that −

  • P and Q are both subsequences of S

  • For each index i, S[i ] belongs to one and only one of P and Q.

  • P is as lexicographically smallest as possible.

So, if the input is S = "thelightsaber", then the output will be 10 because we need 2 red ones

Notebooks, 3 green notebooks and 5 blue notebooks.

Steps

To solve this problem, we will follow the following steps:

c := S
sort the array c
a := position of (c[0]) in S
delete c from S
print c[0] and S

Example

Let us see the below implementation for better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(string S){
   string c = S;
   sort(c.begin(), c.end());
   int a = S.find(c[0]);
   S.erase(S.begin() + a);
   cout << c[0] << ", " << S << endl;
}
int main(){
   string S = "thelightsaber";
   solve(S);
}

Input

"thelightsaber"

Output

a, thelightsber

The above is the detailed content of C++ code to find two substrings with a minimum substring. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete