Given an array of characters which form a sentence of words, give an efficient algorithm to reverse

Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.

 

 

 

 

 

 

 

 

 

 

 

import java.util.ArrayList;
import java.util.List;

public class Reverse {

 public static void main(String args[]) {
  String sentence = "one world one dream";
  List<String> words = new ArrayList<String>();

  int j = 0;
  for (int i = 0; i < sentence.length(); i++) {
   if (sentence.charAt(i) == ' ') {
            words.add(sentence.substring(j,i ));
            j=i+1;
   }
  }
  words.add(sentence.substring(j));
  
  
  for(int i=0;i<words.size()/2;i++)
  {
   String temp=words.get(i);
   words.set(i,words.get(words.size()-i-1));
   words.set(words.size()-i-1,temp);
  }
  
  for(int i=0;i<words.size();i++)
     System.out.print(words.get(i)+" ");
  
 }

}

 

你可能感兴趣的:(Algorithm,String,Class)