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){// Write your code here/* * Ideas: 1. Selecting an element that is smallest in a specific substring on the right of the string and swap it with the element (e) next to the left of that substring, which is also in the string. 2. After that, sort characters on the right of that e in increment order. * Steps to identify the smallest element to swap 1. Traverse from right to left until finds a element that is smaller than the right one. 2. Then, there is at least 1 way to swap. 3. Find the smallest one by traversing until satisfy the requirement */intcur=w.length()-1;intleft=cur-1;//Find the first of two elements to switchwhile(left>-1&&w.charAt(left)>=w.charAt(cur)){cur--;left--;}if(left==-1)return"no answer";//Find the second oneintmid=cur;while(mid<w.length()-1&&w.charAt(mid+1)>w.charAt(left))mid++;char[]tempC=w.toCharArray();//SwapchartempSwap=tempC[left];tempC[left]=tempC[mid];tempC[mid]=tempSwap;char[]tempRSub=newchar[w.length()-cur];for(inti=cur;i<w.length();i++){tempRSub[i-cur]=tempC[i];}//Get new substringArrays.sort(tempRSub);for(inti=cur;i<w.length();i++){tempC[i]=tempRSub[i-cur];}returnnewString(tempC);}
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 solution in Java language: