剑指offer面试题42翻转单词顺序VS左旋字符串

/*
书上书很多公司用这个题 特别大众化
就是一个句里 反转所有单词的顺序 但是单词内部不能变
可以通过两次反转 第一次全反了 第二次 把每个单词的再返回来
刚才查了一下reverse函数 只能C++ 容器用啊。。
所以还是自己写吧
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

void Reverse(char * begin,char  * end)
{
    if(begin==NULL || end==NULL) return;
    while(begin<end)
    {
        char tmp=*begin;
        *begin=*end;
        *end=tmp;
        begin++;
        end--;
    }
}
void ReverseSentence(char * begin)
{
    if(begin==NULL) return ;
    char * end=begin;
    while(*end!='\0')
    end++;
    end--;
    Reverse(begin,end);
    end=begin;
    cout<<begin<<endl;
//这种函数写起来就是挺麻烦的。。
    while(*begin!='\0')
    {
        if(*begin==' ')
        {
            begin++;
            end++;
        }
        else if(*end==' ' ||  *end=='\0')
        {
            Reverse(begin,--end);
            begin=++end;
        }
        else
        end++;
    }
}
/*
 接下来就是string的左旋操作 左旋n位就是把开始的n个字符移动到末尾。
 这样其实挺简单想的 但是不能有额外空间开销 那只能一个一个的倒 时间复杂度又太高。。
 和上面的思想一样 先全部逆过来 再把前后两半各自逆过来
 或者先把前后两半逆过来也行 再全逆过来
*/
void LeftRotatedString(char * str,int n)
{
    char * begin=str,*end=str;
    while(n--)
    end++;
    Reverse(begin,--end);//先把前一段弄好
    begin=++end;
    while(*end!='\0')
    ++end;
    Reverse(begin,--end);//再把后一段弄好
    begin=str;
    Reverse(begin,end);
}
int main()
{
    char str[]="I am a student.";
    int size=(sizeof str/sizeof *str)-1;
    //Reverse(str,str+size-1);//开始这里传入参数有问题了。。size 那么求出来还有最后一额\0
    cout<<str<<endl;
    ReverseSentence(str);
    cout<<str<<endl;
    char str2[]="abcdefg";
    LeftRotatedString(str2,4);
    cout<<str2<<endl;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值