LeetCode | 344 Reverse String

分析

字符数组本质上还是数组,双指针本质上是遍历,遍历过程只处理两个独立数据,移动过程将问题分为已经解决和未解决的两部分。
在这个题目中值得注意的是,关于字符数组进行数据原地交换采用的是异或^的方式

主类

package com.github.dolphinmind.string;

/**
 * @author dolphinmind
 * @ClassName ReverseString
 * @description
 * @date 2024/8/9
 */

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

        if (s == null || s.length <=0) {
            return;
        }

        int low = 0;
        int high = s.length - 1;

        while (low < high) {
            /**
             * 使用异或运算来交换变量通常被认为是一种技巧性的做法,而不是一种标准做法
             */
//            s[low]  ^= s[high];
//            s[high] ^= s[low];
//            s[low]  ^= s[high];

            char temp = s[low];
            s[low] = s[high];
            s[high] = temp;
            low++;
            high--;
        }
    }
}


测试

package com.github.dolphinmind.string;

import org.junit.Test;

/**
 * @author dolphinmind
 * @ClassName ReverseStringTest
 * @description
 * @date 2024/8/9
 */

public class ReverseStringTest {

    @Test
    public void test_ReverseString() {
//        char[] s = {'h','e','l','l','o'};

        char[] s = {};

        ReverseString reverseString = new ReverseString();
        reverseString.reverseString(s);
        System.out.println(s);
    }
}

posted @ 2024-08-09 17:45  Neking  阅读(5)  评论(0编辑  收藏  举报