java将字符串逆序递归方式输出

来源:互联网 发布:mac用itunes制作铃声 编辑:程序博客网 时间:2024/05/17 06:44

最近找到这样的一个题目,如何将字符串采用递归方式输出:

如将字符串"hello world my friend and now"--〉now and friend my world hello

实现这个方法很多,我的方法可能效率比较低下,如果有更好的方法请指教。

public static void main(String[] args) {System.out.println(reserve(""));}public static String reserve(String str){String objstr="hello world my friend and now";Object[] array=objstr.split(" ");Object[] nowarry=str.split(" ");array=compare(array, nowarry);if(array.length<1){return str;}for(int i=array.length-1;i>=0;i--){str=str+" "+array[i];reserve(str);}return str;}private static Object[] compare(Object[] array,Object[] nowarry){List<Object> endList=new ArrayList<Object>();List<Object> ownList=new ArrayList<Object>();for(int i=0;i<array.length;i++){for(int j=0;j<nowarry.length;j++){if(array[i].equals(nowarry[j])){ownList.add(array[i]);}}endList.add(array[i]);}endList.removeAll(ownList);return  endList.toArray();}

[结果展示]: now and friend my world hello

需要注意的是:在系统中当采用String[] 标识数组时,进行endList.toArray()转换,会出现classCastException异常。所以将上面的String全部换成Object对象。


如果有更简单的实现方式请不吝赐教。谢谢

0 0
原创粉丝点击