Posted on

Description

Submission

  • Front behind to front, find the first pair of decreasing letters
  • Find the number that is just bigger in the second part and swap it with the pair.first
  • Sort the second part
  • The special cases are when the string has 0 or 1 letters or the string is is already in decreasing order
#include <bits/stdc++.h>

using namespace std;

// Complete the biggerIsGreater function below.
string biggerIsGreater(string w) {
    if(w.size() <= 1) return "no answer";

    for(int i = w.size() - 1; i >= 1; --i) {
        if(w[i-1] < w[i]) {
            // find the just bigger one
            int index = w.size();
            for(int j = i; j < w.size(); ++j) {
                if(index == w.size() && w[j] > w[i-1]) index = j;
                else if(w[j] > w[i-1] && w[j] < w[index]) index = j;
            }
            if(index == w.size()) return "no answer";
            swap(w[i-1], w[index]);
            sort(w.begin() + i, w.end());
            return w;
        }
    }
    return "no answer";
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    int T;
    cin >> T;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    for (int T_itr = 0; T_itr < T; T_itr++) {
        string w;
        getline(cin, w);

        string result = biggerIsGreater(w);

        fout << result << "\n";
    }

    fout.close();

    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *