LeetCode-探索-初级-字符串-反转字符串-java

编写一个函数,其作用是将输入的字符串反转过来。

示例 1:

输入: "hello"
输出: "olleh"

示例 2:

输入: "A man, a plan, a canal: Panama"
输出: "amanaP :lanac a ,nalp a ,nam A"

方法可以有很多,任君选择,总体思路就是反转数组即可:

1.反转方式

2.循环的"/2"可以利用">>1"替代d

后面是我写的几种方法:

public String reverseString(String s) {
        char[] chars = s.toCharArray();
        int limit = chars.length / 2;
        int symmetryI = 0;
        for (int i = 0 ; i < limit ; i ++) {
            symmetryI = chars.length - 1 - i;
            chars[i] = (char) (chars[i] ^ chars[symmetryI]);
            chars[symmetryI] = (char)(chars[i] ^ chars[symmetryI]);
            chars[i] = (char)(chars[i] ^ chars[symmetryI]);
        }
        return new String(chars);
    }

    public String reverseString0(String s) {
        char[] chars = s.toCharArray();
        int limit = chars.length >> 1;
        char temp = 0;
        int symmetryI = 0;
        for (int i = 0 ; i < limit ; i ++) {
            symmetryI = chars.length - 1 - i;
            temp = chars[i];
            chars[i] = chars[symmetryI];
            chars[symmetryI] = temp;
        }
        return new String(chars);
    }

    public String reverseString1(String s) {
        char[] chars = s.toCharArray();
        char[] target = new char[chars.length];
        for (int i = chars.length - 1 ; i >= 0 ; i --)
            target[chars.length - 1 - i] = chars[i];
        return new String(target);
    }

    public String reverseString2(String s) {
        return new StringBuilder(s).reverse().toString();
    }

利用位运算来进行 /2 或者两个数交换的技巧在之前应该说过,不在赘述

你可能感兴趣的:(LeetCode)