编程珠玑 Chapter2 字符串翻转算法
2012-09-27 22:02
288 查看
没办法,久没练过算法,只好用Java写了。
题目很简单:
Q: abcdefg, r=3
A: defgabc
代码一:借助StringBuffer的append来做。即一部分一部分来求逆,然后再“拼接”起来求逆。
代码二:不用append,对原字符串一部分一部分进行求逆操作,再整体求逆。求逆用的是围绕“中间点”交换字符来做的。
两者效率差不太多,后者略高一点。(遍历一半的距离)
题目很简单:
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)); } }
两者效率差不太多,后者略高一点。(遍历一半的距离)
相关文章推荐
- 编程珠玑--杂技算法--字符串、数组的旋转
- 【字符串算法】——KMP算法、压缩字符串、字符串镜像、翻转字符串
- 经典算法面试题目-翻转一个C风格的字符串(1.2)
- python 数字 字符串 翻转算法
- 【编程珠玑】第十五章--字符串:统计文本中单词数量(C++的Map&C的结构体实现&POJ2418)
- 翻转子串 假定我们都知道非常高效的算法来检查一个单词是否为其他字符串的子串。请将这个算法编写成一个函数,给定两个字符串s1和s2,请编写代码检查s2是否为s1旋转而成,要求只能调用一次检查子串的函数。
- 字符串循环移位 - 编程珠玑的一道题
- 程序员编程艺术(算法卷):第一章、左旋转字符串
- Swift算法实现逐字翻转字符串的方法示例
- 编程实现字符串中各单词的翻转
- 编程:字符串翻转Java
- 程序员编程艺术(算法卷):第一章、左旋转字符串
- 编程珠玑 ~~ 啊哈! 算法
- LintCode 算法(简单)翻转字符串
- 编程珠玑之第一章习题5:k趟算法给1000w数据排序的测试用例
- FCC算法:一、Reverse a String--翻转字符串
- 蛮力法:设计算法求解字符串的模式匹配问题,并编程实现。
- 编程珠玑 第十五章 散列表应用 hash字符串
- 编程珠玑: 15章 字符串 15.2寻找字符串中的最长重复子串 -------解题总结