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