Leetcode: Reverse Words in a String II, leetcodereverse

Source: Internet
Author: User

Leetcode: Reverse Words in a String II, leetcodereverse

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 are always separated by a single space.For example,Given s = "the sky is blue",return "blue is sky the".Could you do it in-place without allocating extra space?

This question requires in-place practice and cannot use extra space. The practice is very similar to that of Rotate Array.

(1) reverse the whole array

(2) reverse each subarray seperated''

 1 public class Solution { 2     public void reverseWords(char[] s) { 3         if (s.length == 0) return; 4         reverse(s, 0, s.length-1); 5         int last = 0; 6         for (int i=0; i<s.length; i++) { 7             if (s[i] == ' ') { 8                 reverse(s, last, i-1); 9                 last = i + 1;10             }11         }12     }13     14     public void reverse(char[] s, int l, int r) {15         while (l <= r) {16             int temp = s[l];17             s[l] = s[r];18             s[r] = temp;19             l++;20             r--;21         }22     }23 }

 

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.