344.Reverse String

Solution 1: accepted 17ms 3.83%

In your dream.

1
2
3
4
5
6
7
public String reverseString(String s) {
StringBuilder sb = new StringBuilder();
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i) + ""); // charAt() is too expensive
}
return sb.toString();
}

Solution 2: accepted 4ms

Well, this is cheating XD. Try to imagine and implement what’s inside the function.

1
2
3
4
public String reverseString(String s) {
StringBuilder sb = new StringBuilder(s);
   return sb.reverse().toString(); // reverse() has bitwise implementation so it's pretty fast
}

Solution 3: accepted 2ms 77.7%

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public String reverseString(String s) {
// if (s.length() < 2) return s; // no impact on performance
char[] A = s.toCharArray(); // implementation: java.lang.System.arraycopy()
int l = 0;
int r = A.length - 1;
while (l < r) {
char temp = A[l];
A[l] = A[r];
A[r] = temp;
l++;
r--;
}
return String.valueOf(A);
}