Given a string array that either contains empty strings or non-empty strings, arrange the contents such that all the empty strings are at front and non-empty strings at back, retaining their order from original array.
For example, input:
{"","a","","d","","o","","g",""} {"d","o","g"} {"","","",""}
Output:
[, , , , , a, d, o, g] [d, o, g] [, , , ]
I wrote two implementations below:
In-place re-arrangement
//in-place arrangement with two pointers running towards starting index from back public static void arrangeString(String...arr) { for (int i=arr.length-1, j=i; i>=0 && j >=0; ) { boolean needSwap =false; boolean exit = false; while (!exit && arr[i].equals("")) { i--; needSwap = true; if (i==-1) exit = true; } while (!exit && !arr[j].equals("")) { j--; needSwap = true; if (j==-1) exit = true; } if (exit) break; if (needSwap) { String temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } i--; j--; } }
Re-arranging using a temp array
public static String[] arrangeString(String...arr) { int len = arr.length; String[] temp = new String[len]; for (int i=0, t1=0, j=len-1, t2=len-1; i<len && j>=0; i++, j--) { if(arr[i].equals("")) temp[t1++] = arr[i]; else if(!arr[j].equals("")) temp[t2--] = arr[j]; } return temp; }
Please give me suggestions on how to improve them. It'll be great if you can provide an alternative code snippet replacing my code.