《剑指offer-43》左旋转字符串的两种c++解法

题目描述

汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!

解法1:分成两段对字符串进行左移,建立零时的string存储前n个字符防止字符串被覆盖。

class Solution {
public:
    string LeftRotateString(string str, int n) {
        int length=str.length();
        if(length<0)
            return NULL;
        string tmp;
        for(int i=0;i<n;i++)
        {
            tmp[i]=str[i];
        }
        for(int i=0;i<length-n;i++){
            str[i]=str[i+n];
        }
        for(int i=length-n,a=0;i<length;a++,i++){
            str[i]=tmp[a];
        }
        return str;
    }
};

解法2:通过三次翻转字符串的方式获得最终想要的字符串。

class Solution {
public:
    string LeftRotateString(string str, int n) {
        string result = str;
        int length = result.size();
        if(length < 0){
            return NULL;
        }
        if(0 <= n <= length){
            int pFirstBegin = 0, pFirstEnd = n - 1;
            int pSecondBegin = n, pSecondEnd = length - 1;
            ReverseString(result, pFirstBegin, pFirstEnd);
            ReverseString(result, pSecondBegin, pSecondEnd);
            ReverseString(result, pFirstBegin, pSecondEnd);
        }
        return result;
    }
private:
    void ReverseString(string &str, int begin, int end){
        while(begin < end){
            swap(str[begin++], str[end--]);
        }
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_42056625/article/details/88136768