说明:算法很好,可以看看
package edu.yhf.demo; /** * 反转测试 * way1:翻转单词顺序,递归调用 * way2:先按照空格拆分,然后排序,再按照空格拼接即可. * @author lengzl * @email [email protected] * @create 2017年2月8日 上午9:37:36 */ public class Reverse { /** * * @author lengzl * @email [email protected] * @create 2017年2月8日 上午10:13:01 * @param array 结束位置,array.length-1 * @param start 初始位置:通常为0 * @param end */ public void Reverse(char[] array,int start,int end){ if(array == null||start<0||end>array.length -1){ return; } while(start<end){ char temp = array[start]; array[start] = array[end]; array[end] = temp; start++; end--; } newString(array); } /** * 1.普通字符反转 * @author lengzl * @email [email protected] * @create 2017年2月8日 上午10:21:42 * @param array */ public void Reverse(char[] array){ int start = 0; int end = array.length-1; if(array == null||start<0||end>array.length -1){ return; } while(start<end){ char temp = array[start]; array[start] = array[end]; array[end] = temp; start++; end--; } newString(array); } public void newString(char[] array){ System.out.println(String.valueOf(array)); } /** * way1:翻转单词顺序,递归调用 * @author lengzl * @email [email protected] * @create 2017年2月8日 上午11:24:48 * @param sentence */ public void ReverseSentence(String sentence){ if(sentence.isEmpty()||sentence==null){ return; } char[] array = sentence.toCharArray(); int start = 0; int end = array.length - 1; //S1:先反转整个句子 Reverse(array,start,end); //S2:再反转居中的每个单词. start = end = 0; while (start < array.length){ if(array[start] == ' '){ start++; end++; //如果遇到空格,就可以反转 }else if(end == array.length||array[end]==' '){ /*说明: * end一直从0开始,追踪到最后一个字符,不再反转. * start为每个char的初始位置; * */ Reverse(array, start, --end); //只有一个单词也反转 start = end + 1; end++; }else{ end++; } } newString(array); } /** * way2:先按照空格拆分,然后排序,再按照空格拼接即可. * @author lengzl * @email [email protected] * @create 2017年2月8日 上午11:24:06 * @param sentence */ public void reverseSplit(String sentence){ String[] array = sentence.split(" "); String[] arrayReverse = reverseArray2(array); StringBuffer sb = new StringBuffer(); for (int i = 0; i < arrayReverse.length; i++) { if(i==arrayReverse.length-1){ sb.append(arrayReverse[i]); }else{ sb.append(arrayReverse[i]).append(' '); } } System.out.print(sb); } /** * 数组直接反转 * @author lengzl * @email [email protected] * @create 2017年2月8日 上午10:57:23 * @param Array * @return */ private String[] reverseArray2(String[] Array) { String[] new_array = new String[Array.length]; for (int i = 0; i < Array.length; i++) { // 反转后数组的第一个元素等于源数组的最后一个元素: new_array[i] = Array[Array.length -1- i ]; } return new_array; } public static void main(String[] args) { Reverse r= new Reverse(); /*普通反转字符. char[] array = {'A','B','C','D'}; r.Reverse(array);*/ //way2:递归调用式反转 //r.ReverseSentence("I am a student"); r.reverseSplit("I am a student."); } //way3:直接按照空格拆分,然后重新排序组合. }