Saturday, June 3, 2017

344. Reverse String

Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".



Solution:

Use two pointers from two side to move into the middle.

In each round exchange the elements between two pointers.

The time complexity is O(n) and the space complexity is O(n).



Code:


public class Solution {
    public String reverseString(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        int i = 0;
        int j = s.length() - 1;
        char[] arr = s.toCharArray();
        while (i < j) {
            char swap = arr[i];
            arr[i++] = arr[j];
            arr[j--] = swap;
        }
        return new String(arr);
    }
}