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.
publicstaticStringbiggerIsGreater(Stringw){char[]charArray=w.toCharArray();intn=charArray.length;// Step 1: Find the rightmost character that is smaller than its next characterintindex=-1;for(inti=n-2;i>=0;i--){if(charArray[i]<charArray[i+1]){index=i;break;}}// If no such character exists, it's the last permutationif(index==-1){return"no answer";}// Step 2: Find the smallest character on the right of `index` that is larger than charArray[index]intswitchIndex=-1;for(inti=n-1;i>index;i--){if(charArray[i]>charArray[index]){switchIndex=i;break;}}// Step 3: Swap the characters at `index` and `switchIndex`chartemp=charArray[index];charArray[index]=charArray[switchIndex];charArray[switchIndex]=temp;// Step 4: Sort the substring after `index` to get the next lexicographical orderArrays.sort(charArray,index+1,n);returnnewString(charArray);}
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 →
Java