左旋字符串算法

原题来自《Programming Pearls》,记录在此作为读书笔记。指定长度为n个字符的字符串,实现将其左旋i位的算法。如abcdefgh左旋3位为defghabc。

记原字符串为S,将其分为两个子串,S=A+B。记len(x)表示为字符串x的长度。其中A的长度为i,B的长度为len(s)-i。定义+为字符串拼接操作。

解法一,用临时字符串T记录A,然后将B左移i位,再将T拼接回B之后。
public static void rotate1(char[] src, int i) {
	char[] t = new char[i];
	for(int k=0;k<i;k++) {
		//Store leftmost i characters to t
		t[k] = src[k];
	}
	for(int k=i;k<src.length;k++) {//move right characters to fill the left space
		src[k-i] = src[k];
	}
	for(int k=0;k<i;k++) {
		//Store leftmost i characters to t
		src[src.length - i + k] = t[k];
	}
}


神解法二,定义运算reverse为字符串逆序,如 reverse(AB) = B+A。那么reverse有以下特点。
reverse( reverse(A) ) = A,自己与自己为逆运算。
reverse( reverse(A)+reverse(B))=B+A, 令C=reverse(A),D=reverse(B),
则reverse( reverse(A)+reverse(B)) = reverse(C+D) = reverse(D)+reverse( C) = reverse(reverse(B))+reverse(reverse(A)) =B+A

public static void reverse(char[] input, int start, int end) {
	for (int i = start; i <= (start+end)/2; i++) {
		//(start+end)/2 is the middle of the input
		swap(input, i, start + end - i); 
		//start+end-i is the mirror position of i to(start+end)/2. Let y-(start+end)/2=(start+end)/2 - i. Then y = (start+end) - i;
}
}

public static void rotate2(char[] src, int i) {
	reverse(src, 0, i - 1);
	reverse(src, i, src.length - 1);
	reverse(src, 0, src.length - 1);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值