Java算法之字符串反转分析
本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处!
在基本的工作内容开发中,算法不会显得那么重要,而在百万级别的时候,差距非常大,今天带大家研究下常见的字符串反转算法。
public class StringReverse { public static String reverse1(String orig) { char[] s = orig.toCharArray(); int n = s.length - 1; int halfLength = n / 2; for (int i = 0; i <= halfLength; i++) {// 2分法+替换算法 char temp = s[i]; s[i] = s[n - i]; s[n - i] = temp; } return new String(s); } public static String reverse2(String s) {// 2分法+异或算法 char[] str = s.toCharArray(); int begin = 0; int end = s.length() - 1; while (begin < end) { str[begin] = (char) (str[begin] ^ str[end]); str[end] = (char) (str[begin] ^ str[end]); str[begin] = (char) (str[end] ^ str[begin]); begin++; end--; } return new String(str); } public static String reverse3(String s) {// jdk提供 return new StringBuffer(s).reverse().toString(); } public static String reverse4(String s) {// 2分递归算法 int length = s.length(); if (length <= 1) return s; String left = s.substring(0, length / 2); String right = s.substring(length / 2, length); return reverse1(right) + reverse1(left); } public static String reverse5(String s) {// 傳統从后往前加 int length = s.length(); String reverse = ""; for (int i = 0; i < length; i++) reverse = s.charAt(i) + reverse; return reverse; } public static String reverse6(String s) {//傳統與5雷同 char[] array = s.toCharArray(); String reverse = ""; for (int i = array.length - 1; i >= 0; i--) reverse += array[i]; return reverse; } public static String reverse7(String s) {// 利用栈先进后出的特性 char[] str = s.toCharArray(); Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < str.length; i++) stack.push(str[i]); String reversed = ""; for (int i = 0; i < str.length; i++) reversed += stack.pop(); return reversed; } public static void main(String[] args) { String str = "hello world !"; int length = 10000000; long curTime = System.currentTimeMillis(); for (int i = 0; i < length; i++) { reverse1(str); } System.out.println("reverse1:" + (System.currentTimeMillis() - curTime)); curTime = System.currentTimeMillis(); for (int i = 0; i < length; i++) { reverse2(str); } System.out.println("reverse2:" + (System.currentTimeMillis() - curTime)); curTime = System.currentTimeMillis(); for (int i = 0; i < length; i++) { reverse3(str); } System.out.println("reverse3:" + (System.currentTimeMillis() - curTime)); curTime = System.currentTimeMillis(); for (int i = 0; i < length; i++) { reverse4(str); } System.out.println("reverse4:" + (System.currentTimeMillis() - curTime)); curTime = System.currentTimeMillis(); for (int i = 0; i < length; i++) { reverse5(str); } System.out.println("reverse5:" + (System.currentTimeMillis() - curTime)); curTime = System.currentTimeMillis(); for (int i = 0; i < length; i++) { reverse6(str); } System.out.println("reverse6:" + (System.currentTimeMillis() - curTime)); curTime = System.currentTimeMillis(); for (int i = 0; i < length; i++) { reverse7(str); } System.out.println("reverse7:" + (System.currentTimeMillis() - curTime)); } }