每日两道算法题 - 字符串反转(高频)

问题

给定一个字符串数组,将数组内元素进行反转。需在当前数组中原地交换。
输入:"h","e","l","l","o"
输出:"o","l","l","e","h"

思路

双指针
定义一个指针left指向数组头部
定义一个指针right指向数组尾部
left不断自增,right不断自减。当left小于right时,则交换指针在数组内对应元素。

image.png

实现

public class ReverseString {

    public static void main(String[] args) {

        String[] chars = new String[]{"h","e","l","l","o"};
        String[] result = doubleIndex(chars);
        System.out.println(Arrays.toString(result));
    }

    //双指针
    private static String[] doubleIndex(String[] chars) {
        int length = chars.length;
        int left = 0;
        int right = length-1;
        while (left < right){
            doubleIndexSwap(chars,left++,right--);
        }
        return chars;
    }

    private static void doubleIndexSwap(String[] chars, int left, int right) {
        String temp = chars[left];
        chars[left] = chars[right];
        chars[right] = temp;
    }
}
image.png

你可能感兴趣的:(每日两道算法题 - 字符串反转(高频))