I wrote this program which reverses the words in a given string. Please review and give your inputs.
private static void reverseWords(String value) {
// reverse the whole string
value = reverseInOofN2Time(value);
// now split (on space) the string into an string array
String[] strArr = value.split(" ");
// make it empty
value = "";
for (int i = 0; i < strArr.length; i++) {
// reverse each strArr element and append it to the value
value += reverseInOofN2Time(strArr[i]) + " ";
}
System.out.println(value);
}
public static String reverseInOofN2Time(String h) {
char[] charArr = h.toCharArray();
for (int i = 0; i < charArr.length / 2; i++) {
char temp = charArr[i];
int targetPos = (charArr.length - 1) - i;
charArr[i] = charArr[targetPos];
charArr[targetPos] = temp;
}
return new String(charArr);
}
reverseInOofN2Time
when the time is \$O(n)\$ and not \$O(n^2)\$? And in fact, why do you even reverse the string only to reverse it back later? – JS1 Jul 2 at 2:07reverseInOn2Time()
anywhere in the code, either. – Hosch250 Jul 2 at 15:01