zoukankan      html  css  js  c++  java
  • (剑指Offer)面试题42:左旋转字符串

    题目:

    字符串的左旋转操作是把字符串前面的若干字符转移到字符串的后面。请定义一个函数实现字符串左旋转操作的功能,

    比如:输入字符串"abcdefg"和数字2,该函数将返回左旋转2位得到的结果"cdefgab";

    思路:

    这道题和翻转单词顺序很相似。思路也是一样的。

    第一步:翻转整个字符串"abcdefg",得到"gfedcba"

    第二步:翻转字符串“gfedc”,得到"cdefg"

    第三步:翻转字符串"ba",得到"ab"

    或者:

    第一步:翻转字符串“ab”,得到"ba";

    第二步:翻转字符串"cdefg",得到"gfedc";

    第三步:翻转字符串"bagfedc",得到"cdefgab";

    代码:

    #include <iostream>
    #include <string.h>
    
    using namespace std;
    
    void Reverse(char* pBegin,char* pEnd){
        if(pBegin==NULL || pEnd==NULL)
            return;
        char tmp;
        while(pBegin<pEnd){
            tmp=*pBegin;
            *pBegin=*pEnd;
            *pEnd=tmp;
            pBegin++;
            pEnd--;
        }
    }
    
    char* LeftRotateString(char* pStr,int n){
        int len=strlen(pStr);
        if(pStr==NULL || n<=0 || n>=len)
            return pStr;
        char* pFirstStart=pStr;
        char* pFirstEnd=pStr+n-1;
        char* pSecondStart=pStr+n;
        char* pSecondEnd=pStr+len-1;
    
        Reverse(pFirstStart,pFirstEnd);
        Reverse(pSecondStart,pSecondEnd);
        Reverse(pFirstStart,pSecondEnd);
    
        return pStr;
    }
    
    int main()
    {
        char A[]="abcdefg";
        int k=2;
        cout << LeftRotateString(A,k) << endl;
        return 0;
    }

    在线测试OJ:

    http://www.nowcoder.com/books/coding-interviews/12d959b108cb42b1ab72cef4d36af5ec?rp=2

    AC代码:

    class Solution {
    public:
        string LeftRotateString(string str, int n) {
            int len=str.length();
            if(len<=1 || n<=0 || n>=len)
                return str;
            
            int pFirstStart=0;
            int pFirstEnd=n-1;
            int pSecondStart=n;
            int pSecondEnd=len-1;
            
            Reverse(str,pFirstStart,pFirstEnd);
            Reverse(str,pSecondStart,pSecondEnd);
            Reverse(str,pFirstStart,pSecondEnd);
            
            return str;
        }
        
        void Reverse(string &str,int pBegin,int pEnd){
            char tmp;
            while(pBegin<pEnd){
                tmp=str[pBegin];
                str[pBegin]=str[pEnd];
                str[pEnd]=tmp;
                pBegin++;
                pEnd--;
            }
        }
    };
  • 相关阅读:
    2015-05-06前端开发总结
    深入了解 Flexbox 伸缩盒模型
    Sublime text3 快捷方式(windows平台)
    移动web最简洁的滑动效果Swipe JS(适合初学者)
    谈响应式web设计代码实现
    经验分享:多屏复杂动画CSS技巧三则
    css3 animation动画效果解析
    移动H5前端性能优化指南
    php codeigniter (CI) oracle 数据库配置-宋正河整理
    jquery图片裁切+PHP文件上传
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4683277.html
Copyright © 2011-2022 走看看