LeetCode - 344 - Reverse String

Problem

Write a function that takes a string as input and returns the string reversed.

Example:

Given s = “hello”, return “olleh”.

Try it out : http://leetcode.com/problems/reverse-string/

Java - 2ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
public String reverseString(String a) {
if(a == null) return null;
if(a.equals("")) return a;
char[] s = a.toCharArray();
int swapEnd = s.length/2;
for(int i=0,j=s.length-1;i<swapEnd;i++)
{
//s = swap(s,i,s.length-1-i);
char temp = s[j-i];
s[j-i] = s[i];
s[i] = temp;
}
return String.valueOf(s);
}
public char[] swap(char[] a,int posF, int posE)
{
char temp = a[posE];
a[posE] = a[posF];
a[posF] = temp;
return a;
}
}

Javascript -160ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @param {string} s
* @return {string}
*/
var reverseString = function (s) {
if (!s) {
return "";
}
var rs = "";
for (var i = s.length; i >= 0; i--) {
rs += s.charAt(i);
}
return rs;
};