Update

One new tab added. Open in browser view if it is not visible. (25/08/2022 08:48)

Bigger is Greater

Language : C++
(NOTE : Try a few times yourself before moving to the solution)


#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);

/*
 * Complete the 'biggerIsGreater' function below.
 *
 * The function is expected to return a STRING.
 * The function accepts STRING w as parameter.
 */

string biggerIsGreater(string w) {
    int n = w.length();
    int j, k;
    for (j = n - 2; j >= 0; j--)
        {
        for (k = n - 1; k > j && w[k] <= w[j]; k--)
                            ;
            if (k == j)     continue;
            char tmp = w[k];
            w[k] = w[j];
            w[j] = tmp;
            sort(w.begin() + j + 1, w.end());
        break;
        }
            if (j < 0)
                    w= "no answer" ;
    return w;
    
}

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

    string T_temp;
    getline(cin, T_temp);

    int T = stoi(ltrim(rtrim(T_temp)));

    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;
}

string ltrim(const string &str) {
    string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun(isspace)))
    );

    return s;
}

string rtrim(const string &str) {
    string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(),
        s.end()
    );

    return s;
}

  

No comments: