int index[20] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
//output: word by word sentence this reverse
//order : O(n/2) + O(n) + O(w)*O(wlen/2)
//find indexes of words' start
void revsentence(char* src, int len)
{
for(int i=0; i< len/2; i++)
{
char temp = src[i];
src[i] = src[len-i-1];
src[len-i-1] = temp;
}
int j=1;
for(int i=0; i< len; i++)
{
if(src[i] == ' ')
index[j++] = i;
}
index[j++] = len; //last index = src:'\0'
//reverse the words
for(int i=0; i< j; i++)
{
int startindex = index[i] + 1;
int endindex = index[i+1]-1;
int wlen = endindex - startindex +1;
for(int k=0; k< wlen/2; k++)
{
char temp = src[startindex+k];
src[startindex+k] = src[endindex-k];
src[endindex-k] = temp;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char src[200];
cout << "enter a string to reverse word by word: " ;
cin.getline(src,200);
revsentence(src, strlen(src));
cout << "\noutput: " << src << endl;
return 0;
}
No comments:
Post a Comment