Monday, August 15, 2022
HomeSoftware DevelopmentLexicographically smallest String by transferring one Subsequence to the top

Lexicographically smallest String by transferring one Subsequence to the top

[ad_1]

  

#embrace <bits/stdc++.h>

utilizing namespace std;

  

string LexMin(int n, string s)

{

    

    

    vector<int> final(26, -1);

    for (int i = 0; i < n; i++) {

        final[s[i] - 'a'] = i;

    }

    int dig = 0;

    int mx = 26;

  

    

    

    string ans = s, ans1, ans2;

    for (int i = 0; i < n; i++) {

  

        

        

        whereas (dig < 26 && i > final[dig])

            dig++;

        if (dig == mx) {

            string ans3 = ans2, ans4;

            for (int j = i; j < n; j++) {

  

                

                if (s[j] == ('a' + mx)) {

                    ans4.push_back(s[j]);

                }

                else {

                    ans3.push_back(s[j]);

                }

            }

  

            

            

            ans2 += s.substr(i);

  

            

            

            ans = min(ans, ans1

                               + min(ans2, ans4 + ans3));

            break;

        }

        else if (dig > mx) {

            ans = min(ans, ans1

                               + ans2 + s.substr(i));

            break;

        }

  

        

        if (s[i] == ('a' + dig)) {

            ans1.push_back(s[i]);

        }

        else {

            if (mx == 26)

                mx = (s[i] - 'a');

            ans2.push_back(s[i]);

        }

  

        

        if (i == n - 1)

            ans = min(ans, ans1 + ans2);

    }

  

    

    return ans;

}

  

int essential()

{

    int N = 3;

    string s = "asa";

  

    

    cout << LexMin(N, s) << endl;

    return 0;

}

[ad_2]

RELATED ARTICLES

Most Popular

Recent Comments