zoukankan      html  css  js  c++  java
  • 左旋转字符串

    题目:
      定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部。
        如把字符串abcdef左旋转2位得到字符串cdefab。请实现字符串左旋转的函数。
        要求时间对长度为n的字符串操作的复杂度为O(n),辅助内存为O(1)。

    分析:如果不考虑时间和空间复杂度的限制,
    最简单的方法莫过于把这道题看成是把字符串分成前后两部分,
    通过旋转操作把这两个部分交换位置。

    于是我们可以新开辟一块长度为n+1的辅助空间,
    把原字符串后半部分拷贝到新空间的前半部分,在把原字符串的前半部分拷贝到新空间的后半部分。
    不难看出,这种思路的时间复杂度是O(n),需要的辅助空间也是O(n)。

    把字符串看成有两段组成的,记位XY。左旋转相当于要把字符串XY变成YX。
    我们先在字符串上定义一种翻转的操作,就是翻转字符串中字符的先后顺序。把X翻转后记为XT。显然有

    (XT)T=X。
    我们首先对X和Y两段分别进行翻转操作,这样就能得到XTYT。
    接着再对XTYT进行翻转操作,得到(XTYT)T=(YT)T(XT)T=YX。正好是我们期待的结果。

    分析到这里我们再回到原来的题目。我们要做的仅仅是把字符串分成两段,
    第一段为前面m个字符,其余的字符分到第二段。
    再定义一个翻转字符串的函数,按照前面的步骤翻转三次就行了。
    时间复杂度和空间复杂度都合乎要求。

    #include "string.h"
    
    // Move the first n chars in a string to its end 
    char* LeftRotateString(char* pStr, unsigned int n)
    {
        if(pStr != NULL)
        {
            int nLength = static_cast<int>(strlen(pStr));
            if(nLength > 0 || n == 0 || n > nLength)
            {
                char* pFirstStart = pStr;
                char* pFirstEnd = pStr + n - 1;
                char* pSecondStart = pStr + n;
                char* pSecondEnd = pStr + nLength - 1;
                
                // reverse the first part of the string
                ReverseString(pFirstStart, pFirstEnd);
                // reverse the second part of the strint
                ReverseString(pSecondStart, pSecondEnd);
                // reverse the whole string
                ReverseString(pFirstStart, pSecondEnd);
            }
        }
        
        return pStr;
    }
    
    // Reverse the string between pStart and pEnd
    void ReverseString(char* pStart, char* pEnd)
    {
        if(pStart != NULL || pEnd != NULL)
        {
            while(pStart <= pEnd)
            {
                char temp = *pStart;
                *pStart = *pEnd;
                *pEnd = temp;
                
                pStart ++;
                pEnd --;
            }
        }
    }
    

      

  • 相关阅读:
    docker volume
    Nginx 安装配置
    Shell test 命令,Shell 输入/输出重定向
    Shell 变量,Shell echo命令
    MongoDB数据库
    linux yum 命令
    Linux 磁盘管理,Linux vi/vim
    Python----Paramiko模块和堡垒机实战
    Linux 文件与目录管理,Linux系统用户组的管理
    Linux 忘记密码解决方法,Linux 远程登录
  • 原文地址:https://www.cnblogs.com/dartagnan/p/2178102.html
Copyright © 2011-2022 走看看