We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
My logic is:
To find the next bigger string, we should start from the end of string, and find the first character that can be exchanged with something bigger on its right. Swap those chars. So, this new string has everything same with original string till the left of this exchange position. Just sort everything right of this position and we got the next possible bigger string.
for (i = 0; i < t; i++)
{
string w;
cin >> 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)
cout << "no answer" << endl;
else
cout << w << endl;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Bigger is Greater
You are viewing a single comment's thread. Return to all comments →
My logic is: To find the next bigger string, we should start from the end of string, and find the first character that can be exchanged with something bigger on its right. Swap those chars. So, this new string has everything same with original string till the left of this exchange position. Just sort everything right of this position and we got the next possible bigger string.