Java实现字符串反转

一、代码

package algorithm;

import java.util.Stack;

public class ReverseString {

    /**
     * 逆序遍历实现字符串反转
     *
     * @param string
     * @return
     */
    public static String reverse(String string) {
        if (null == string || string.length() <= 0) {
            return null;
        }

        StringBuffer sb = new StringBuffer();
        for (int i = string.length() - 1; i >= 0; i--) {
            char c = string.charAt(i);
            sb.append(c);
        }

        return sb.toString();
    }

    /**
     * 字符串转数组, 交换左右字符实现字符串反转
     *
     * @param string
     * @return
     */
    public static String reverse2(String string) {
        if (null == string || string.length() <= 0) {
            return null;
        }

        int left = 0;
        int right = string.length() - 1;
        char[] chars = string.toCharArray();
        while (left < right) {
            char charLeft = string.charAt(left);
            char charRight = string.charAt(right);
            chars[left] = charRight;
            chars[right] = charLeft;
            left++;
            right--;
        }

        return new String(chars);
    }

    /**
     * 栈具有后进先出的特点, 可以利用栈实现字符串反转
     *
     * @param string
     * @return
     */
    public static String reverse3(String string) {
        if (null == string || string.length() <= 0) {
            return null;
        }

        Stack<Character> stack = new Stack<>();

        // 入栈
        for (int i = 0; i < string.length(); i++) {
            stack.push(string.charAt(i));
        }

        // 出栈, 将pop出的元素放入字符数组chars中
        char[] chars = string.toCharArray();
        for (int i = 0; i < string.length(); i++) {
            chars[i] = stack.pop();
        }

        return new String(chars);
    }

    public static void main(String[] args) {
        System.out.println(reverse("abcdefg"));
        System.out.println(reverse2("abcdefg"));
        System.out.println(reverse3("abcdefg"));
    }

}

二、运行结果

运行结果

posted @ 2019-04-07 11:30 wangzaiplus 阅读(...) 评论(...) 编辑 收藏