July 31, 2016 · JS Java Algorithm LeetCode

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

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

/**
 * @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;
};