字符串单词翻转

题目要求:将字符串以词为单位进行翻转。如:"a bc def gh ij kml"变成"kml ij gh def bc a"。时间复杂度O(n),空间复杂度O(1)。

思路:先将整个字符串按字母进行翻转,然后再逐个单词翻转。

代码如下:

#include<iostream>
using namespace std;

void wordturn(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;
   }
 
   //寻找空格,翻转单词的字母
   char *phead = src;
   char *ptail = src;
   while('\0' != *phead && '\0' != *ptail){
      if(*ptail == ' '){
         int word_len = ptail - phead;
         for(int j=0 ; j < word_len/2; j++){
            char temp = phead[j];
            phead[j] = phead[word_len-1-j];
            phead[word_len-1-j] = temp;
         } 
         phead = ptail +1;
      }
    ptail++;
   }
}

 

int main(){
   char src[] = "  a bc   def gh ij kml   ";
   char *psrc = src;
   int len = sizeof(src)/sizeof(char);
   cout << src << endl;
   wordturn(psrc,len-1);
   cout << src << endl;

  return 0;
}

posted @ 2013-04-03 22:26  Tiu.G  阅读(172)  评论(0编辑  收藏  举报