• (剑指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--;
            }
        }
    };
  • 相关阅读:
    20070521_新疆出差纪实
    有想应聘技术咨询顾问职位的朋友请看过来
    Access:運作必須查詢3/19
    我們是好朋友1/3
    小說學習1/22
    [Asp.net]動態設定標簽寬度2/22
    [Asp.net]HyperLinkColumn應用2/28
    [Asp.net]重啟IIS2/29
    [Asp.NET]水晶報表與網路密碼2/27
    把學習量化3/6
  • 原文地址:https://www.cnblogs.com/AndyJee/p/4683277.html
Copyright © 2020-2023  润新知