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

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

如将字符串"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对象。

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

你的脸是为了呈现上帝赐给人类最贵重的礼物–微笑,一定要成为你工作最大的资产。

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

相关文章:

你感兴趣的文章:

标签云: