Problem
Write a function that takes a string as input and returns the string reversed.
Example
Given s = "hello"
, return "olleh"
.
Solution
1. Two-Pointer --3ms
public class Solution {
public String reverseString(String s) {
char[] str = s.toCharArray();
int left = 0, right = str.length-1;
while (left < right) {
char temp = str[left];
str[left] = str[right];
str[right] = temp;
left++;
right--;
}
return new String(str);
}
}
2. StringBuilder --5ms
public class Solution {
public String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}
}
3. Recursion --22ms
public class Solution {
public String reverseString(String s) {
int len = s.length();
if (len <= 1) return s;
String leftStr = s.substring(0, len / 2);
String rightStr = s.substring(len / 2, len);
return reverseString(rightStr) + reverseString(leftStr);
}
}