• 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"));
        }
    
    }
    

    二、运行结果

    运行结果

  • 相关阅读:
    Linux shell 学习总结
    linux shell 比较总结
    NSURL基本操作 HA
    Mac node.js install HA
    nodejs学习资料收集 HA
    xcode技巧 HA
    google web app/enxtions 学习资料收集 HA
    Failed to upload *.app on Device 可能的解决方法 HA
    iphone开发常见问题小集2 HA
    cocos2d收集 HA
  • 原文地址:https://www.cnblogs.com/wangzaiplus/p/10664467.html
Copyright © 2020-2023  润新知