Last Substring in Lexicographical Order

Given a string s, return the last substring of s in lexicographical order.

Example:

Input: s = "abab"
Output: "bab"
Explanation: The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

string lastSubstring(string s)
{
    int i = 0j = 0p = 1k = 0;
    while (p < s.size())
    {
        if (s[p] > s[i])
        {
            i = p;
            p++;
            continue;
        }
        if (s[p] == s[i])
        {
            k = p;
            j = i;
            while (p < s.size() and s[j] == s[p] and j < k)
            {
                p++;
                j++;
            }
            if (j < k and s[j] < s[p])
            {
                i = k;
            }
            continue;
        }
        p++;
    }
    return s.substr(i);
}

int main()
{
    string s = "abab";

    cout << lastSubstring(s);

    return 0;
}


No comments:

Post a Comment