牛客网-C++剑指offer-第四十二题(左旋转字符串)

题目描述

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

 

解题思路:

用string队列解决来解决。

 

参考代码:

#include <iostream>
#include <string.h>
#include <vector>
#include <stack>
#include <queue>
#include<algorithm>
#include <string>

using namespace std;

class Solution {
public:
    string LeftRotateString(string str, int n) {

        if (str.empty())
            return str;

        string my_temp;

        for (int i = 0; i < n; ++i) {
            my_temp.push_back(str.front());
            str.erase(str.begin());
           // cout<<"res:"<<my_temp<<endl;
        }

        for (int j = 0; j < n; ++j) {
            str.push_back(my_temp.front());
            my_temp.erase(my_temp.begin());
        }

        return str;
    }
};

int main()
{
    Solution solution;

    string my_str = "abcXYZdef";

    //solution.LeftRotateString(my_str,3);
    cout<<"res:"<<solution.LeftRotateString(my_str,3);

    return 0;
}

 

优化代码:

//时间复杂度为O(n)
class Solution {
public:
    string LeftRotateString(string str, int n) {
        if (str.empty() || n > str.size() || n < 1)
            return str;

        string my_res;
        for (int i = n; i < str.size(); ++i) {
            my_res.push_back(str[i]);
        }

        for (int j = 0; j < n; ++j) {
            my_res.push_back(str[j]);
        }

        return my_res;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值