Java very simple to understand O(n) solution


#1

Comment body goes here.`public class Solution {
public String solve(String A) {
char[]ch1=A.toCharArray();
int[]ch=new int[ch1.length];
for(int i =0;i<ch1.length;i++){
ch[i]=ch1[i]-48;
}
int index=-1;
for(int i=A.length()-1;i>0;i–){
if(ch[i]>ch[i-1]){
index= i-1;
break;
}
}
if(index==-1){
return “-1”;
}
else{
int swapWithIndex=-1;
for(int j=A.length()-1;j>index;j–){
if(ch[j]>ch[index]){
swapWithIndex=j;
break;
}
}
int temp=ch[index];
ch[index]=ch[swapWithIndex];
ch[swapWithIndex]= temp;

       Arrays.sort(ch,index+1,ch.length);
    }
String str=Arrays.toString(ch);
String ans="";
for(int i=0;i<ch.length;i++ ){
   ans+=ch[i]; 
}
return ans;
        
    }
    
}

`