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.