Taking into account the following statement:
If the string has even characters without any numeric value then swap the adjacent and if string contains odd [number of] characters then print invalid string as output
The solution may be as follows:
public static String solve(String str) {
String result = "Invalid string"; // prepare result
if (null != str && str.length() % 2 == 0) { // check the null and length of the input
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i += 2) {
if (Character.isDigit(arr[i]) || Character.isDigit(arr[i + 1])) {
// if any digit found, return "Invalid string"
return result;
}
// do the swap
char t = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = t;
}
// make the result string
result = new String(arr);
}
return result;
}
Tests:
String[] tests = {
"abcd", "AB", "", "AAaaBBbb", // even length
"1234", // digits
"AbCdE", "A", // odd length
null,
"A.B+C-D!" // even length without digits
};
for (String t : tests) {
System.out.printf("%s -> %s%n", t, solve(t));
}
Output:
abcd -> badc
AB -> BA
->
AAaaBBbb -> AAaaBBbb
1234 -> Invalid string
AbCdE -> Invalid string
A -> Invalid string
null -> Invalid string
A.B+C-D! -> .A+B-C!D
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…