https://leetcode.com/problems/reverse-string/
https://discuss.leetcode.com/topic/43997/using-recursion-only-1-line-but-time-exceeded
Write a function that takes a string as input and returns the string reversed.
public String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}
public String reverseString(String s) {
char[] c = s.toCharArray();
for (int i=0,j=c.length-1;i<j;i++,j--){
char temp = c[i];
c[i]=c[j];
c[j]=temp;
}
return new String(c);
}
https://leetcode.com/discuss/98774/many-acceptable-answers
Same as previous but using byte instead
public class Solution {
public String reverseString(String s) {
byte[] bytes = s.getBytes();
int i = 0;
int j = s.length() - 1;
while (i < j) {
byte temp = bytes[i];
bytes[i] = bytes[j];
bytes[j] = temp;
i++;
j--;
}
return new String(bytes);
}
}
Classic Method by swapping first and last
If you don't like temp variable
If you don't like temp variable
public class Solution {
public String reverseString(String s) {
byte[] bytes = s.getBytes();
int i = 0;
int j = s.length() - 1;
while (i < j) {
bytes[i] = (byte)(bytes[i] ^ bytes[j]);
bytes[j] = (byte)(bytes[i] ^ bytes[j]);
bytes[i] = (byte)(bytes[i] ^ bytes[j]);
i++;
j--;
}
return new String(bytes);
}
}
Using recursion
public class Solution {
public String reverseString(String s) {
int length = s.length();
if (length <= 1) return s;
String leftStr = s.substring(0, length / 2);
String rightStr = s.substring(length / 2, length);
return reverseString(rightStr) + reverseString(leftStr);
}
}
https://discuss.leetcode.com/topic/43997/using-recursion-only-1-line-but-time-exceeded
public String reverseString(String s) {
return s.length()<=1?s:(reverseString(s.substring(1))+s.charAt(0));
}