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.
importjava.io.*;importjava.util.*;importjava.lang.StringBuilder;publicclassSolution{publicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */Scannerinput=newScanner(System.in);intT=input.nextInt();input.nextLine();for(inti=0;i<T;i++){Stringword=input.nextLine();if(word.length()==1){System.out.println("no answer");continue;}intmaxLexoC1=0;//The max lexocographical according to condition 1intmaxLexoC2=0;//The max lexocographical according to condition 2//Find the largest index char that is weakly increasing such as g in hefg for(intj=1;j<word.length();j++){booleancondition1=word.charAt(j)>word.charAt(j-1);if(condition1){maxLexoC1=(j>maxLexoC1)?j:maxLexoC1;}}//if our only increasing is at point 0 then we are in the last permuation of our stringif(maxLexoC1==0){System.out.println("no answer");continue;}//maxLexoC2//Determine the right most char greater than the pivot in index and in lexofor(intj=maxLexoC1;j<word.length();j++){booleancondition2=word.charAt(j)>word.charAt(maxLexoC1-1);if(condition2){maxLexoC2=j;}}StringBuilderwordSB=newStringBuilder(word);//Swap the pivot with maxLexoC2chartmp=wordSB.charAt(maxLexoC1-1);wordSB.setCharAt(maxLexoC1-1,wordSB.charAt(maxLexoC2));wordSB.setCharAt(maxLexoC2,tmp);//Reverse starting at the element to the right of the pivotintleft=maxLexoC1;intright=wordSB.length()-1;while(left<right){//swap left with righttmp=wordSB.charAt(left);wordSB.setCharAt(left,wordSB.charAt(right));wordSB.setCharAt(right,tmp);left++;right--;}System.out.println(wordSB);}}}
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 →