344 Reverse String

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

Example:
Given s = "hello", return "olleh".

Solution)

Using a swapping left and right

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

results matching ""

    No results matching ""