One question per day: reverse English sentences

Source: Internet
Author: User

Reversing English sentences means reversing the order of the words in the sentence, as shown in the following example:
Input: Wo shi Zhong guo ren
Output: ren guo zhong shi wo
The intuitive solution is to first extract each word, and then calculate the position of each word reversal, and finally fill in the corresponding position of the word. This scheme occupies not only the auxiliary space, but also the computational complexity. Another option is to see the whole sentence as a string, reverse the order of the string letters (including spaces), and then reverse the alphabetical order of each word. The reversal of the word letter means:
Input: Wo shi Zhong guo ren
Output: Ner oug gnohz IHS ow
Here is the code for the second way of thinking:

#include "stdafx.h"#include <string.h>#include <iostream>#include <vector>using namespace STD;voidReverseString (CharStr[],intStartintEnd) { for(inti = Start,j = end; I < J; ++i,--j) {Charc = Str[i];        Str[i] = Str[j];    STR[J] = c; }}voidReverseString (CharStr[]) {intLength =strlen(str); ReverseString (str,0, Length-1);}voidReversesentence (CharStr[]) {reversestring (str); vector<int>Splitindex;intLength =strlen(str);//Record the position of the word separator (space), place a dummy space at the beginning of the sentenceSplitindex.push_back (-1); for(inti =0; i < length; ++i) {if(Str[i] = ="') Splitindex.push_back (i); }//end of sentence place a dummy spaceSplitindex.push_back (length);intCount = Splitindex.size ()-1; for(inti =0; I < count; ++i) {reversestring (Str,splitindex[i] +1, splitindex[i+1] -1); }}int_tmain (intARGC, _tchar* argv[]) {CharStr[] ="wo shi Zhong guo ren";cout<<str<<endl; Reversesentence (str);cout<<str<<endl;return 0;}

Program run:

The program only considers the English alphabet input, and does not consider punctuation, all words separated by a space.

One question per day: reverse English sentences

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.