The sword refers to the offer----flip the word order column----Java implement the order in which the words are flipped

Source: Internet
Author: User

New Ket recently had a new employee fish, who always held an English magazine every morning and wrote some sentences in the book. Colleague Cat was interested in what Fish had written, and one day he borrowed it from fish to read it, but he couldn't understand what it meant. For example, "student." A am I ". It was later realized that the guy had flipped the order of the words in the sentence and the correct sentence would be "I am a student." Cat is not good at one by one flipping these words, can you help him.

Ideas:

(1) Flip the whole sentence first

(2) Flip each word again

When you flip each word, use two variables to control, start is the beginning of the word, end is the space after the word, each flip character interval between the start~end-1

Note: The last word is not a space

  public string reversesentence (String str)
	  {
	       if (str = NULL | | Str.length () <2) 
	       {return
	    	   str;
	       }
	       char[] array = Str.tochararray ();
	       Reserve (ARRAY,0,ARRAY.LENGTH-1);
	       int start = 0;//records the starting position of each word
	       int end = 0;//Word's ending position while
	       (ends < Array.Length)
	       {
	    	   if (array[end)!= ')
	    	   {
	    		   if (end = = array.length-1)//The last word has no space
	    		   {
	    			   reserve (array,start,end);
	    		   }
	    		   end++;
	    	   }
	    	   else if (array[end]== ')///When a space is encountered, flip the word before the space and set the start to end
	    	   {
	    		   reserve (array,start,end-1);
	    		   end++;
	    		   Start = end;//The starting position of the next word
	    	   } return
	       string.valueof (array)
	  ;
	  private void Reserve (char[] array,int start,int end)
	  {
		  char temp = ';
		  while (Start < end)
		  {
			  temp = Array[start];
			  array[start++] = Array[end];
			  array[end--] = temp;
		  }
	  }



Related Article

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.