字符串的旋转

来源:互联网 发布:瑞星防火墙软件 编辑:程序博客网 时间:2024/05/29 13:38

把字符串”abcdef”转换为”defabc”,行话:把字符串的前n个字符放在字符串的后面。
思路:

  • 首先,把字符串的前n个字符先对调,即:abc->cba
  • 然后,把剩余的字符串对调,即:def->fed
  • 最后,把整个字符串都对调,即:cbafed->defabc
#include "iostream"#include "string"using namespace std;void shiftString(string& str,int start , int end){    while(start<end)    {        char c;        c=str[start];        str[start]=str[end];        str[end]=c;        start++;        end--;    }}void reverseString(string& str, int shiftNum , int strNum){    if(shiftNum<strNum)    {        shiftString(str,0,shiftNum-1);        shiftString(str,shiftNum,strNum-1);        shiftString(str,0,strNum-1);    }}int main(){    string str="abcdef";    reverseString(str);    cout<<str<<endl;    //Good luck!    return 0;}
0 0