This is interview question
Reverse string with identical spaces as in original String using Java
For example
Original String :
best in the world and is greatest and is making sure the world goes well
Output:
llew se ogd lrowe hte ru sgnikams idn at setaer gsid nad lrowe htni tseb
The code I have written is as below:
import java.util.ArrayList;
import java.util.List;
public class CountSpaces {
public static void main(String[] args) {
String st = "best in the world and is greatest and is making sure the world goes well";
String st1 = st;
char[] x = st.toCharArray();
int flag = 0;
List<Integer> spacePositionArray = new ArrayList<Integer>();
int len = x.length;
int sub = 0;
for (int i = 1; i < len; i++) {
char y = x[i];
if (y == ' ') {
if (flag > 0)
spacePositionArray.add(i - sub);
else
spacePositionArray.add(i);
flag++;
sub++;
}
}
st = st.replaceAll("\\s+", "");
x = st.toCharArray();
len = x.length;
int k = 1;
for (int i = len - 1; i >= 0; i--) {
if (spacePositionArray.contains(k)) {
System.out.print(x[i] + " ");
}
else
System.out.print(x[i]);
k++;
}
System.out.println();
System.out.println(st1);
}
}
Can it be done in a much simpler which is more logical. My approach is much more brute and direct.
Kindly review