/*
书上书很多公司用这个题 特别大众化
就是一个句里 反转所有单词的顺序 但是单词内部不能变
可以通过两次反转 第一次全反了 第二次 把每个单词的再返回来
刚才查了一下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;
}