3ms Java Solution


  • 0
    X

    public class Solution {
    public String reverseString(String s) {
    if (s == "" || s.length() <= 1) {
    return s;
    }
    char[] arr = s.toCharArray(); // convert the string to char array

        int left = 0; // the beginning index
        int right = arr.length - 1; // end index
        while (left < right) { // stop when left and right are next to each other
            swap (arr, left, right);
            left++;
            right--;
        }
        return new String(arr, 0, arr.length);
    }
    
    private void swap (char[] arr, int left, int right) {
        char tmp = arr[left];
        arr[left] = arr[right];
        arr[right] = tmp;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.