import java.util.Stack; public class ReverseString { public static void main(String[] args) { System.out.println(reverse1("abcd")); System.out.println(reverse2("abcd")); System.out.println(reverse3("abcd")); System.out.println(reverse4("abcd")); System.out.println(reverse5("abcd")); System.out.println(reverse6("abcd")); System.out.println(reverse7("abcd")); } public final static String reverse1(String str) { return new StringBuilder(str).reverse().toString(); } public final static String reverse2(String str) { String result = ""; int len = str.length(); for (int i = 0; i < len; i++) { result = str.charAt(i) + result; } return result; } public final static String reverse3(String str) { String result = ""; for (int i = str.length() - 1; i >= 0; i--) { result = result + str.charAt(i); } return result; } public final static String reverse4(String str) { int len = str.length(); Stack<Character> stack = new Stack<Character>(); char[] cs = str.toCharArray(); for (int i = 0; i < len; i++) { stack.push(str.charAt(i)); } for (int i = 0; i < len; i++) { cs[i] = stack.pop(); } return new String(cs); } public final static String reverse5(String str) { int len = str.length(); if (len == 1) return str; String left = str.substring(0, len >>> 1); String right = str.substring(len >>> 1, len); return reverse5(right) + reverse5(left); } public final static String reverse6(String str) { int len = str.length(); char[] cs = str.toCharArray(); for (int i = 0, j = len - 1; i < len >>> 1; i++, j--) { cs[i] = str.charAt(j); cs[j] = str.charAt(i); } return new String(cs); } public final static String reverse7(String str) { int len = str.length(); char[] cs = str.toCharArray(); for (int i = 0; i < len >>> 1; i++) { cs[i] ^= cs[len - 1 - i]; cs[len - 1 - i] ^= cs[i]; cs[i] ^= cs[len - 1 - i]; } return new String(cs); } }
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦