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 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦