I have been asked to solve following problem lower than N^2 time complexity and O(N) space complexity:
Write program for the following case Reverse string :
Input:- "Hello World" Output:-"olleH dlroW"
I have tried to figure it out a lot, but whatever I try, I can not come up with a time complexity which is lower than N^2, my code can be seen below, do you have any suggestion how can I come up with a solution with linear time?
Note : it is not allowed to use built-in methods
public static String stringReverser(String str) {
if (str == null || str.isEmpty()) {
throw new IllegalArgumentException();
}
if (str.length() < 2) {
return str;
}
String[] strArr = str.split(" ");
StringBuffer newHolder = new StringBuffer();
for (int i = 0; i < strArr.length; i++) {
int j = 0;
int len = strArr[i].length();
char[] newCharStr = strArr[i].toCharArray();
while (j < len) {
char temp = newCharStr[j];
newCharStr[j] = newCharStr[len - 1];
newCharStr[len - 1] = temp;
len--;
j++;
}
newHolder.append(String.valueOf(newCharStr));
if(i != strArr.length-1){
newHolder.append(" ");
}
}
return newHolder.toString();
}