【剑指offer-解题系列(44)】左旋转字符串
来源:互联网 发布:矩阵方程ax=b 编辑:程序博客网 时间:2024/06/06 21:02
题目描述
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
分析
对于原本需要左移动的字符串 "abcXYZdef ",如果左移动3位,就变成 : "XYZdef" + "abc", 则
设:n=3,N=9(字符串总长度)
可以遍历一遍数组,使用两个ind1=0,ind2,一个ind1指向开头,一个ind2指向移动后的第一个开头字符。
ind1保持不变,ind2每次减去 n(n=3),如果n<0,n = n+N。
原本ind2位置的数字被置换到0位置,则ind2的目标位置是在ind2-n。
在n不被N整除情况下,可以最终遍历完数组,但是n会被N整除的情况下则无法完成遍历
但是为了防止n会被N整除,可以把n减去1
代码实现
string LeftRotateString(string str, int n) {
int N = str.size();
if(N<=0||n<=0||N==n)return str;
int sign = 0;
if(N%n==0&&n!=1){
n-=1;
sign=1;
}
int position_now = 0;
int position_target = -n+N;
while(position_now!=position_target){
swap(str[position_now],str[position_target]);
//cout<<position_now<<" "<<position_target<<endl;
position_target = position_target-n;
while(position_target<0)
position_target+=N;
}
if(sign){
char tmp = str[0];
auto a = str.begin();
for(;a!=str.end()-1;a++){
*a=*(a+1);
}
*a=tmp;
}
return str;
}
- 【剑指offer-解题系列(44)】左旋转字符串
- 剑指offer系列源码-左旋转字符串
- 剑指offer 44 左旋转字符串
- 剑指offer(40)-左旋转字符串
- 【剑指offer】左旋转字符串
- 剑指offer--左旋转字符串
- 《剑指offer》左旋转字符串
- 剑指offer:左旋转字符串
- 剑指offer 左旋转字符串
- [剑指offer]左旋转字符串
- 剑指offer|左旋转字符串
- 《剑指offer》-左旋转字符串
- 剑指offer-左旋转字符串
- 剑指offer:左旋转字符串
- 《剑指offer》左旋转字符串
- 剑指offer--左旋转字符串
- 剑指offer:左旋转字符串
- 剑指offer:左旋转字符串
- 动态提交使用jQuery 完成ajax 文件下载
- 线段树,数据结构,RMQ,分治法,最大和(Magician,HDU 5316)
- PHP的运行模式小结
- phpstorm使用快捷键
- 算法概论习题证明
- 【剑指offer-解题系列(44)】左旋转字符串
- 构建MySQL+DRBD+heartbeat高可用
- 中文输入法onkeydown的bug
- linux笔记-----续
- caffe-windows直接安装版---编译后的Release
- redis集群安装
- SpringMVC之AJAX带分页的增删改查
- LeetCode 581. Shortest Unsorted Contimuous Subarray
- 用linux写一个博客