字符串按特定分隔符反转

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

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


#include <stdio.h>
#include <iostream>

using namespace std;

/*reverse a word*/
void reverseWord(char *pStart, char *pEnd)
{
    while(pStart < pEnd)
    {
        char temp = *pStart;
        *pStart++ = *pEnd;
        *pEnd--   = temp;
    }
}

/*reverse a whole sentense*/
void reverseSentense(char *pStart, char *pEnd)
{
    while(pStart < pEnd)
    {
        char temp = *pStart;
        *pStart++ = *pEnd;
        *pEnd--   = temp;
    }
}

void reverse(char szCh[], char splitor)
{
    if(szCh == NULL)
        return;
    char *pStart = szCh;
    char *pEnd = szCh;
    while(*pEnd)
    {
        if(*pEnd == splitor)
        {
            reverseWord(pStart, pEnd-1);
            pEnd++;
            pStart=pEnd;
        }
        else
        {
            pEnd++;
        }
    }
    reverseWord(pStart, pEnd-1);    //reverse the last word
    reverseSentense(szCh, pEnd-1);  //reverse the whole sentense
}

int main()
{
    //test1
    char szCh[] = "www.taobao.com";
    char splitor = '.';
    cout<<"original: "<<szCh<<endl;
    reverse(szCh, splitor);
    cout<<"output: "<<szCh<<endl;

    //test2
    char szCh2[] = "sports.sina.com.cn";
    char splitor2 = '.';
    cout<<"original: "<<szCh2<<endl;
    reverse(szCh2, splitor2);
    cout<<"output: "<<szCh2<<endl;

    //test3
    char szCh3[] = "fdafd.";
    char splitor3 = '.';
    cout<<"original: "<<szCh3<<endl;
    reverse(szCh3, splitor3);
    cout<<"output: "<<szCh3<<endl;

    //test3
    char szCh4[] = ".fdafd";
    char splitor4 = '.';
    cout<<"original: "<<szCh4<<endl;
    reverse(szCh4, splitor4);
    cout<<"output: "<<szCh4<<endl;

    getchar();
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值