Suppose we have s as string, we have to find the last substring of s in lexicographic order.
So, if the input is like "abbbcabbc", then the output will be "cabbc"
To solve this, we will follow these steps −
i := 0,j := 1,k := 0
while j + k < size of s, do &minsu;
if s[i + k] is same as s[j + k], then −
(increase k by 1)
Ignore following part, skip to the next iteration
if s[i + k] < s[j + k], then −
i := j
(increase j by 1)
Otherwise
j := j + k + 1
k := 0
return substring of s from index i to end
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string lastSubstring(string s) {
int i = 0;
int j = 1;
int k = 0;
while(j + k < s.size()){
if(s[i + k] == s[j + k]) {
k++;
continue;
}
if(s[i + k] < s[j + k]){
i = j;
j++;
}else{
j = j + k + 1;
}
k = 0;
}
return s.substr(i, s.size() - i);
}
};
main(){
Solution ob;
cout << (ob.lastSubstring("abbbcabbc"));
}Input
"abbbcabbc"
Output
cabbc