亲宝软件园·资讯

展开

java字符串反转

负债程序猿 人气:0

1、用stringBuffer或者stringBuilder自带的reverse方法

    public static String reverseTestOne(String s) {
        return new StringBuffer(s).reverse().toString();
    }

2、将字符串拆分为char数组

    public static String reverseTestTwo(String s) {
        char[] charArray = s.toCharArray();
        int start = 0, end = charArray.length - 1;
        for (; start < end; start++, end--) {
            charArray[start] ^= charArray[end];//采用异或
            charArray[end] ^= charArray[start];
            charArray[start] ^= charArray[end];
        }
        return new String(charArray);
    }

两数交换除了用异或还能用其他方法,请移步不借助第三变量实现两数交换

3、stringBuffer倒序拼接

    public static String reverseTestThree(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = s.length() - 1; i >= 0; i--) {
            sb.append(s.charAt(i));
        }
        return sb.toString();
    }

4、利用栈的先进后出

    public static String reverseTestFour(String s) {
        StringBuffer sb = new StringBuffer();
        Stack stack = new Stack();
        for (int i = 0; i < s.length(); i++) {
            stack.push(s.charAt(i));
        }
        while (!stack.isEmpty()) {
            //stack会返回栈顶值,并且会把该值删除
            sb.append(stack.pop());
        }
        return sb.toString();
    } 

5、二分换位反转

    public static String reverseTestFive(String s) {
        int start = 0;
        int end = s.length() - 1;
        char[] charArray = s.toCharArray();
        while (start < end) {
            //交换首尾char值
            char c = charArray[end];
            charArray[end] = charArray[start];
            charArray[start] = c;
            start++;
            end--;
        }
        return new String(charArray);
    }

6、切割递归反转

    public static String reverseTestSix(String s) {
        if (s.length() <= 1) {
            return s;
        }
        return reverseTestSix(s.substring(1)) + s.substring(0, 1);
    }

7、二分递归反转

    public static String reverseTestSeven(String s) {
        int length = s.length();
        if (length <= 1) return s;
        String left = s.substring(0, length / 2);
        String right = s.substring(length / 2, length);
        return reverseTestSeven(right) + reverseTestSeven(left);
    }

加载全部内容

相关教程
猜你喜欢
用户评论