This solution has symmetry symmetry.
public static String transpose(String s) { StringBuilder sb = new StringBuilder(); sb.setLength(s.length()); for (int i = 0, j = s.length() - 1, x = 0; i <= j; ) { sb.setCharAt(x++, s.charAt(i++)); if (i > j) break; sb.setCharAt(x++, s.charAt(j--)); } return sb.toString(); } public static String untranspose(String s) { StringBuilder sb = new StringBuilder(); sb.setLength(s.length()); for (int i = 0, j = s.length() - 1, x = 0; i <= j; ) { sb.setCharAt(i++, s.charAt(x++)); if (i > j) break; sb.setCharAt(j--, s.charAt(x++)); } return sb.toString(); }
This makes it obvious that the logic between the two methods is identical; The only difference is that:
transpose , i and j indicate read indices, x is the write index- In
untranspose , i and j are the write indices, x is the read index (i.e. vice versa)
It is really quite simple:
i always goes from the beginning to the middle of the linej always goes from the end to the middle of the linex always goes from beginning to end of line- If the input is of odd length,
i == j will inevitably end up- At this point you will need
i , so break
Lalit came up with the first recursive solution ; this is the same thing with a slight modification:
public static String transpose(String s) { int L = s.length(); return (L < 2) ? s : s.substring(0, 1) + s.substring(L-1, L) + transpose(s.substring(1, L-1)); } public static String untranspose(String s) { int L = s.length(); return (L < 2) ? s : s.substring(0, 1) + untranspose(s.substring(2, L)) + s.substring(1, 2); }
source share