344. 反转字符串

双指针法

class Solution {
    public void reverseString(char[] s) {

        /**
         * 双指针遍历
         */
        int left = 0;
        int right = s.length - 1;
        char c;

        while (left < right){

            c = s[left];
            s[left++] = s[right];
            s[right++] = c;
        }
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

递归

class Solution {
    public void reverseString(char[] s) {

        /**
         * 递归
         * 因为需要改变索引的位置,因此需要定义一个额外的递归树组
         */
        reverse(s, 0, s.length - 1);
    }

    public void reverse(char[] s, int left, int right){

        /**
         * 将双指针的过程写进递归
         */
        if (left >= right){
            return;
        }

        char temp = s[left];
        s[left] = s[right];
        s[right] = temp;

        reverse(s, left + 1, right - 1);
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

https://leetcode-cn.com/problems/reverse-string/

posted @ 2021-11-24 10:18  振袖秋枫问红叶  阅读(30)  评论(0)    收藏  举报