String reversal-compress contiguous spaces

Source: Internet
Author: User

First, the algorithm description

Given a string, for a string that includes multiple contiguous spaces, compresses and retains only a single space, and a substring that is separated by a space is reversed.

Second, the algorithm thinking

Its essence is a variant of the string reversal, that is, on the basis of the string reversal, but also to compress the extra space, which is more than a simple string reversal of a step to determine the condition of continuous space

The following code, including the simple string reversal function, the implementation is relatively simple, mainly to pay attention to the location of the subscript

Third, the algorithm code

#include <iostream>#include<string.h>#include<stdio.h>#include<stdlib.h>using namespacestd;//string ReversalvoidReverseword (Char*s,intLeftintRight ) {     while(left<Right ) {        CharCh=S[left]; S[left++]=S[right]; S[right--]=ch; }    }//each string reversal in a sentencevoidReversesentence (Char*str) {    intI=0, j=0;  while(str[j]!=' /')    {        if(str[j]==' ') {Reverseword (str,i,j-1); J++; I=J; }        ElseJ++; } reverseword (Str,i,j-1);}//each string in a sentence reverses and compresses extra spaces, leaving only one space between the stringsvoidRemove_space_and_reverse (Char*STR,Char*tstr) {    intI=0, j=0, k=0;  while(str[j]!=' /')    {        if(str[j]==' ') {Tstr[k]=' '; Reverseword (Tstr,i,k-1);  while(str[j]==' ') J++; K++; I=K; }        Else{tstr[k++]=str[j++]; }    }    //reverses the last stringReverseword (tstr,i,k-1);}intMain () {Chars[ the]="ABCEF HIJKLM NOP"; Char*tstr=New Char[ the]; memset (Tstr,0,sizeof(Char)* the);    Remove_space_and_reverse (S,TSTR); cout<<tstr<<Endl; return 0;}

String reversal-compress contiguous spaces

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.