344. Reverse String

O(n), O(1)

class Solution {
    public void reverseString(char[] s) {
        int i = 0;
        int j = s.length - 1;
        
        while(i < j) {
            char temp = s[i];
            s[i] = s[j];
            s[j] = temp;
            i++;
            j--;
        }
    }
}

slower

class Solution {
    public void reverseString(char[] s) {
        for (int i = 0; i < s.length/2; i++) {
            swap(s, i, s.length-1-i);
        }
    }
    private void swap(char[] s, int i, int j) {
        char temp = s[j];
        s[j] = s[i];
        s[i] = temp;
    }
}

Last updated