题目描述
汇编语言中有一种移位指令叫做循环左移(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;
}
};