Leetcode 151st latest question and answer Reverse Words in a String

Source: Internet
Author: User

Reverse Words in a String Total Accepted: 67 Total Submissions: 412My Submissions

Given an input string, reverse the string word by word.

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

Click to show clarification.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Cocould the input string contain leading or trailing spaces?
    Yes. However, your reversed string shocould not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

Leetcode has not updated the question for a long time. It's a coincidence. Today, I just mentioned that I have fixed 150 questions and I will have a new question.

Okay, paste it as soon as possible.

Ideas:

1. traverse the string from the back

2. Save the word and then reverse it. Save it to the result.

Pay attention to the clarification in the question and handle the spaces.

Two additional strings are used to save the intermediate results. The space complexity is O (n ).

The time complexity is O (n). Simple question: 2 to 3 stars

void reverseWords(string &s){string rs;for (int i = s.length()-1; i >= 0; ){while (i >= 0 && s[i] == ' ') i--;if (i < 0) break;if (!rs.empty()) rs.push_back(' ');string t;while (i >= 0 && s[i] != ' ') t.push_back(s[i--]);reverse(t.begin(), t.end());rs.append(t);}s = rs;}




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.