Solution with Java


#1

` public String solve(String A) {
if(A.length()<2) {
return “-1”;
}
String[] a = new String[A.length()];
String[] copy = new String[A.length()];
a = A.split("");
copy = Arrays.copyOf(a, a.length);
Arrays.sort(copy);
if (Arrays.asList(a).toString().equals(Arrays.asList(copy).toString())) {
String temp = a[a.length - 1];
a[a.length - 1] = a[a.length - 2];
a[a.length - 2] = temp;
StringBuffer sb = new StringBuffer();
for (int j = 0; j < a.length; j++) {
sb.append(a[j]);
}
String str = sb.toString();
return str;
}
Collections.reverse(Arrays.asList(copy));
if (Arrays.asList(a).toString().equals(Arrays.asList(copy).toString())) {
return “-1”;
}
for (int i = a.length - 2; i >= 0; i–) {
if (Integer.parseInt(a[i]) < Integer.parseInt(a[i + 1])) {
String temp = “”;
String smallerNum = “”;
int index = 0;
for (int k = i+1; k <=a.length - 1; k++) {
if (Integer.parseInt(a[i]) < Integer.parseInt(a[k])) {
smallerNum = a[k];
index = k;
} else
continue;
}
temp = a[index];
a[index] = a[i];
a[i] = temp;
Arrays.sort(a, i + 1, a.length);
StringBuffer sb = new StringBuffer();
for (int j = 0; j < a.length; j++) {
sb.append(a[j]);
}
String str = sb.toString();
return str;
} else
continue;
}
return “-1”;
}``