编程珠玑 Chapter2 字符串翻转算法

没办法,久没练过算法,只好用Java写了。

题目很简单:

Q: abcdefg, r=3

A: defgabc


代码一:借助StringBuffer的append来做。即一部分一部分来求逆,然后再“拼接”起来求逆。

public class Rotate {

	/**
	 * Rotate a String by reversing it partly and then append them together to
	 * reverse.
	 * 
	 * @param str
	 * @param num
	 * @return
	 */
	public static String rotateStr(String str, int num) {

		StringBuffer tmpStr = new StringBuffer();

		// Note: String#subString() doesn't contain the end index!
		tmpStr = tmpStr.append(reverseStr(str.substring(0, num)));
		tmpStr = tmpStr.append(reverseStr(str.substring(num, str.length())));

		String result = reverseStr(tmpStr.toString());

		return result;
	}

	/**
	 * Reverse a String.
	 * 
	 * @param str
	 * @return
	 */
	private static String reverseStr(String str) {

		int i = str.length() - 1;

		StringBuffer result = new StringBuffer();

		while (i >= 0) {
			result.append(str.charAt(i));
			i--;
		}

		return result.toString();
	}

	public static void main(String[] args) {

		String test = "abcdefghijklmn";

		System.out.println(rotateStr(test, 5));
	}
}

代码二:不用append,对原字符串一部分一部分进行求逆操作,再整体求逆。求逆用的是围绕“中间点”交换字符来做的。


public class Rotateng {

	/**
	 * Reverse part of a StringBuffer specified by start to end.
	 * 
	 * @param str
	 * @param start
	 * @param end
	 * @return
	 */
	public static String reverse(String str, int start, int end) {

		StringBuffer result = new StringBuffer(str);

		// The middle of this part
		int mid = (end + start) / 2;

		for (int i = start; i <= mid; i++) {

			// Calculate the location i should rotated to
			int index = 2 * mid - i;

			// If this part is even, index should be adjusted
			if ((end - start + 1) % 2 == 0) {
				index = index + 1;
			}

			char tmp = result.charAt(i);
			result.setCharAt(i, result.charAt(index));
			result.setCharAt(index, tmp);
		}

		return result.toString();
	}

	/**
	 * Rotate a String by reversing it partly but no append.
	 * 
	 * @param str
	 * @param num
	 * @return
	 */
	public static String rotateStr(String str, int num) {

		int end = str.length() - 1;

		String result=reverse(str, 0, num-1);
		result = reverse(result, num, end);
		result = reverse(result, 0, end);

		return result;
	}

	public static void main(String[] args) {

		String test = "abcdefghijklmn";

		System.out.println(rotateStr(test, 5));
	}
}

两者效率差不太多,后者略高一点。(遍历一半的距离)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值