Reverse String
Question (LC.344)
Given a string, return a reversed string.
Cannot do this in-place since string is immutable in Java.
Example
("") => ""
("ab c") => "c ba"
Brute Force
for n-1 to 0
add it to the new string
L/R Pointers
swap 0 and n-1 until they collide
Code
public String reverseString(String input) {
if (input == null || input.length() <= 1) {
return input;
}
char[] rev = input.toCharArray();
int i = 0, j = input.length() - 1;
while (i < j) {
char temp = rev[j];
rev[j] = rev[i];
rev[i] = temp;
i++;
j--;
}
return String.valueOf(rev);
}
Last updated