zoukankan      html  css  js  c++  java
  • 面试题42-2:左旋转字符串

    题目描述

    字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如输入字符串"abcdefg"和数字2,该函数将返回左旋转2位得到的结果"cdefgab"。

    题目分析

    剑指Offer(纪念版)P220

    代码实现

    void Reverse(char *pBegin, char *pEnd)
    {
        if(pBegin == NULL || pEnd == NULL)
            return;
    
        while(pBegin < pEnd)
        {
            char temp = *pBegin;
            *pBegin = *pEnd;
            *pEnd = temp;
    
            pBegin ++, pEnd --;
        }
    }
    
    char* LeftRotateString(char* pStr, 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;
    
                // 翻转字符串的前面n个字符
                Reverse(pFirstStart, pFirstEnd);
                // 翻转字符串的后面部分
                Reverse(pSecondStart, pSecondEnd);
                // 翻转整个字符串
                Reverse(pFirstStart, pSecondEnd);
            }
        }
    
        return pStr;
    }
    

      

  • 相关阅读:
    PHP设计模式
    PHP 面向对象
    MYSQL 覆盖索引
    MYSQL IOPS、QPS、TPS
    MySQL 事务嵌套
    MySQL 慢查询优化
    MySQL 查询状态
    MySQL 乐观锁和悲观锁
    MySQL 分库、分表
    Spring Boot 全局异常捕捉,自定义异常并统一返回
  • 原文地址:https://www.cnblogs.com/xwz0528/p/4977979.html
Copyright © 2011-2022 走看看