java將字串逆序遞迴方式輸出,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對象。
如果有更簡單的實現方式請不吝賜教。謝謝