I come, I see, I conquer

                    —Gaius Julius Caesar

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

要求:不得开辟额外的空间,而且用递归实现!

C++版:

#include <stdio.h>
#include 
<string>
using namespace std;

void moveSpace(string::iterator& head, string::iterator& newhead, string& str)
{
     
if ( head == str.end())
     {
           
if (newhead != head)  
               
*newhead = '\0'// 新的结尾标志, Just For C API, anybody make sure it's used in std::string?
           return;
     }
     
if ( *head == ' ')
          moveSpace(
++head,newhead,str);
     
else
     {
          
*newhead = * head;
          moveSpace(
++head,++newhead,str);
     }
}

int main()
{
    
//test case1

    
string testStr = "         ";
    
string::iterator h1 = testStr.begin();
    
string::iterator h2 = testStr.begin();
    moveSpace(h1,h2,testStr);
    printf(
"%s\n",testStr.c_str());

   
//test case2

    testStr 
= "    I am man    ! ";
    h1 
= testStr.begin();
    h2 
= testStr.begin();
    moveSpace(h1,h2,testStr);
    printf(
"%s\n",testStr.c_str());

    
//test case3

    testStr 
= "   I a m m a        n !      ";
    h1 
= testStr.begin();
    h2 
= testStr.begin();
    moveSpace(h1,h2,testStr);
    printf(
"%s\n",testStr.c_str());
}
posted on 2008-10-29 00:24  jcsu  阅读(406)  评论(0)    收藏  举报