JCSU

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

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());
}

分类:

技术点:

相关文章: