Reverse String

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

Example:
 Given s = "hello", return "olleh".
public class Solution {
    public String reverseString(String s) {
        if (s == null)
            return s;
        char[] array = s.toCharArray();
        for (int i = 0; i <  s.length()/2; i++) {
            char temp = s.charAt(i);
            array[i] = array[s.length()- i - 1];
            array[s.length()-i-1] = temp;
        }
        return new String(array);
        //ps: a general way to initialize string: String s = new String();
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s