字符串按特定分隔符反转

阿里巴巴的实习生笔试题,实现将字符串按特定分隔符进行反转,如“www.taobao.com”,反转后为"com.taobao.www",要求时间复杂度为O(n),空间复杂度为O(1).

解题思想:用两个指针记录分隔符之间的子字符串,然后先将子字符串进行反转,逐段全部反转后,再将整个字符串进行一次反转


[cpp]  view plain copy
  1. #include <stdio.h>  
  2. #include <iostream>  
  3.   
  4. using namespace std;  
  5.   
  6. /*reverse a word*/  
  7. void reverseWord(char *pStart, char *pEnd)  
  8. {  
  9.     while(pStart < pEnd)  
  10.     {  
  11.         char temp = *pStart;  
  12.         *pStart++ = *pEnd;  
  13.         *pEnd--   = temp;  
  14.     }  
  15. }  
  16.   
  17. /*reverse a whole sentense*/  
  18. void reverseSentense(char *pStart, char *pEnd)  
  19. {  
  20.     while(pStart < pEnd)  
  21.     {  
  22.         char temp = *pStart;  
  23.         *pStart++ = *pEnd;  
  24.         *pEnd--   = temp;  
  25.     }  
  26. }  
  27.   
  28. void reverse(char szCh[], char splitor)  
  29. {  
  30.     if(szCh == NULL)  
  31.         return;  
  32.     char *pStart = szCh;  
  33.     char *pEnd = szCh;  
  34.     while(*pEnd)  
  35.     {  
  36.         if(*pEnd == splitor)  
  37.         {  
  38.             reverseWord(pStart, pEnd-1);  
  39.             pEnd++;  
  40.             pStart=pEnd;  
  41.         }  
  42.         else  
  43.         {  
  44.             pEnd++;  
  45.         }  
  46.     }  
  47.     reverseWord(pStart, pEnd-1);    //reverse the last word  
  48.     reverseSentense(szCh, pEnd-1);  //reverse the whole sentense  
  49. }  
  50.   
  51. int main()  
  52. {  
  53.     //test1  
  54.     char szCh[] = "www.taobao.com";  
  55.     char splitor = '.';  
  56.     cout<<"original: "<<szCh<<endl;  
  57.     reverse(szCh, splitor);  
  58.     cout<<"output: "<<szCh<<endl;  
  59.   
  60.     //test2  
  61.     char szCh2[] = "sports.sina.com.cn";  
  62.     char splitor2 = '.';  
  63.     cout<<"original: "<<szCh2<<endl;  
  64.     reverse(szCh2, splitor2);  
  65.     cout<<"output: "<<szCh2<<endl;  
  66.   
  67.     //test3  
  68.     char szCh3[] = "fdafd.";  
  69.     char splitor3 = '.';  
  70.     cout<<"original: "<<szCh3<<endl;  
  71.     reverse(szCh3, splitor3);  
  72.     cout<<"output: "<<szCh3<<endl;  
  73.   
  74.     //test3  
  75.     char szCh4[] = ".fdafd";  
  76.     char splitor4 = '.';  
  77.     cout<<"original: "<<szCh4<<endl;  
  78.     reverse(szCh4, splitor4);  
  79.     cout<<"output: "<<szCh4<<endl;  
  80.   
  81.     getchar();  
  82.     return 0;  
  83. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值