java將字串逆序遞迴方式輸出,java字串逆序遞迴

來源:互聯網
上載者:User

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對象。


如果有更簡單的實現方式請不吝賜教。謝謝

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.