编程珠玑 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));
	}
}

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

你可能感兴趣的:(Algorithm)