Java outputs the string in reverse recursion mode and java string in reverse recursion Mode

Source: Internet
Author: User

Java outputs the string in reverse recursion mode and java string in reverse recursion Mode

Recently I found a question about how to recursively output strings:

For example, set the string "hello world my friend and now" --> now and friend my world hello

There are many ways to achieve this, and my method may be inefficient. If you have a better method, please advise.

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();}

[Result Display]: now and friend my world hello

Note that when String [] is used to identify an array in the system, endList. toArray () conversion may cause classCastException. Therefore, replace all the above strings with Object objects.


If you have a simpler implementation method, please do not hesitate to inform us. Thank you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.