Leetcode 186. Reverse Words in a String II rotating character array----------java

Source: Internet
Author: User

 

Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.

The input string does not contain leading or trailing spaces and the words is always separated by a single space.

For example,
Given s = " the sky is blue ",
Return " blue is sky the ".

Could do it in-place without allocating extra space?

1, the beginning of the idea is to find the first and last word, and then exchange them two, but the problem is that two words of inconsistent length will be very troublesome, you need to move the remaining strings throughout, cumbersome, and inefficient.

2, reference to discuss, found very simple idea, is divided into two steps: The first step is to put the whole string upside down, the second step is to turn back and then each word reversed once.

 Public classSolution { Public voidReversewords (Char[] s) {intLen =s.length; Reverse (s),0, Len-1); intStart = 0;  for(inti = 0; i < len-1; i++){            if(S[i] = = ") {Reverse (S, start, I-1); Start= i + 1; }} reverse (S, start, Len-1); }    Private voidReverseChar[] s,intStartintend) {         while(Start <end) {            CharCH =S[start]; S[start]=S[end]; S[end]=ch; Start++; End--; }    }}

Leetcode 186. Reverse Words in a String II rotating character array----------java

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.