L344. Reverse String

String

Problem:

Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

Example 1:

Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Solution:

public void reverse(char[] str){
    if(str == null || str.length == 0) return null;
    int left = 0;
    int right = str.length()-1;
    while(left < right){
        swap(s, left++, right--)
    }
}
private void swap(char[] str, left, right){
    char[] temp = str[left];
    str[left] = str[right];
    str[right] = temp; 
}

Last updated

Was this helpful?