码迷,mamicode.com
首页 > 编程语言 > 详细

C++左旋字符串

时间:2015-05-30 21:13:50      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:旋转


//左旋转字符串abcdefgh->cdefghab

//循环递归法
#include <iostream>
#include <string.h>
using namespace std;
void runstring(char *str,int n)
{
    int i = 0;
    int j = i+n;
    int len = strlen(str);
    char *p = str;
    char ch;
    while(j<len)
    {
        for(int m=0;m<n;m++)
        {
            if(p[j]==‘\0‘)break;
            ch = p[i];
            p[i]=p[j];
            p[j]=ch;
            i++;j++;
        }
    }
    //此时defgh cab后面的cab需要在进行旋转.
    for(int k=0;k<n-len%n;k++)
    {
        //最后面需要旋转的字符串是len%n,因为不满足n位,于是我先交换len%n位,
        //这样就只查n-len%n位就可以转换号了,于是我将剩余的部分进行右旋转.
        ch=p[i];
        int m;
        for(m=i;m<len-1;m++)
        {
            p[m]=p[m+1];
        }
        p[m]=ch;
    }

} 
int main()
{
    char str[]="abcdefghmk";
    runstring(str,3);//总共10位,而我们需要3位的转动,则呢么做呢?
    cout<<str<<endl;
    return 0;
}




//<指针反转法>
#include <iostream> //一旦出现移动位数不够的情况就跳出循环,开始移动.
#include <string.h>i
using namespace std;
void runstring(char *str,int n)
{
    if(n<=0 || str==NULL)return;
    //char *fptr = str;
    //char *lptr = str+n;
    char *p  = str;
    int len = strlen(str);
    int i = 0;
    int j = i+n;//
    int k;
    char ch;
    while(len-j>=n)
    {
        for(k=0;k<n;k++)
        {
        ch = p[j];
        p[j] = p[i];
        p[i] = ch;
        i++;
        j++;
        }
    }
    n = len-j;
    for(k=0;k<n;k++)
    {
        ch = p[len-1];
        int sum = len-1;
        for(int m = 0;m<=j-i;m++)
        {
            p[sum] = p[sum-1];
            sum--;
        }
        p[sum]=ch;
    }
}
int main()
{
    char str[]="abcdefghlm";
    runstring(str,4);
    cout<<str<<endl;
    return 0;
}








//<暴力移位法>
#include <iostream>
#include <string.h>
using namespace std;
void runstring(char *str,int n)
{
    if(str==NULL || n==0)return;
    if(n>0)
    {
        for(int i=0;i<n;i++)
        {
            char *p  = str;
            char ch=p[0];
            while(*p!=‘\0‘)
            {
            *p=*(p+1);
            p++;
            }
            *(p-1) = ch;
        }
    }
else
    {
        int m = strlen(str);
        for(int i=0;i<-n;i++)
        {
            char *p = str+m-1;
            char ch = *p;
            int save = m-1; 
            while(m-1>0)
            {   
                *p = *(p-1);
                p--;
                m--;
            }
            *p=ch;
          m=save; 
        }
    }
}
int main()
{
    char str[]="abcdefgh";
    runstring(str,0);
    cout<<str<<endl;
    return 0;
}

C++左旋字符串

标签:旋转

原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/46278059

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!