反转一个字符串的算法
2016-04-03 19:22
344 查看
这个功能在java的JDK中StringBuffer的父类已经实现了,实现代码如下(不相关代码已经省略):
补充说明:需要用2个字符表示一个超大字符集的汉字,这这种表示方式称之为 Surrogate。
abstract class AbstractStringBuilder implements Appendable, CharSequence { /** * The value is used for character storage. */ char[] value; /** * The count is the number of characters used. */ int count; /** * Causes this character sequence to be replaced by the reverse of * the sequence. If there are any surrogate pairs included in the * sequence, these are treated as single characters for the * reverse operation. Thus, the order of the high-low surrogates * is never reversed. * (省略部分注释).... * @return a reference to this object. */ public AbstractStringBuilder reverse() { boolean hasSurrogates = false; //n为字符串长度 int n = count - 1; //循环交换 //(n-1) >> 1 位移算法的结果是取到了对数 for (int j = (n-1) >> 1; j >= 0; j--) { //j是最后一个,n-j是第一个 int k = n - j; //进行交换,从中间向两端交换,如果n为奇数,则第一次交换j和k相等。 char cj = value[j]; char ck = value[k]; value[j] = ck; value[k] = cj; //判断cj和ck是否是合法的字符 if (Character.isSurrogate(cj) || Character.isSurrogate(ck)) { hasSurrogates = true; } } //存在Surrogate,如果存在,循环一次将所有Surrogate位置交换回来,否则无法正常显示了。 if (hasSurrogates) { reverseAllValidSurrogatePairs(); } return this; } /** Outlined helper method for reverse() */ private void reverseAllValidSurrogatePairs() { for (int i = 0; i < count - 1; i++) { char c2 = value[i]; if (Character.isLowSurrogate(c2)) { char c1 = value[i + 1]; if (Character.isHighSurrogate(c1)) { value[i++] = c1; value[i] = c2; } } } } } /** * 省略了部分代码 */ public final class Character implements java.io.Serializable, Comparable<Character> { public static boolean isSurrogate(char ch) { return ch >= MIN_SURROGATE && ch < (MAX_SURROGATE + 1); } //判断字符是否是Surrogate的高位字符 public static boolean isHighSurrogate(char ch) { // Help VM constant-fold; MAX_HIGH_SURROGATE + 1 == MIN_LOW_SURROGATE return ch >= MIN_HIGH_SURROGATE && ch < (MAX_HIGH_SURROGATE + 1); } }
补充说明:需要用2个字符表示一个超大字符集的汉字,这这种表示方式称之为 Surrogate。
相关文章推荐
- 并发编程之基础( 五)
- C++命名规范
- 深度学习核心技术
- android的Services生命周期和使用方法
- C++命名规范
- 单例模式之 懒汉模式普通版
- C#中OnLoad事件和Form1_Load事件的区别
- 导入dmp文件,提示不是有效的导出文件,头部验证失败
- tomcat服务器部署项目问题
- 如何线程安全地遍历List:Vector、CopyOnWriteArrayList
- Mac 键盘快捷键,苹果Macbook电脑快捷键
- cocos2dx 3.1从零学习(一)——入门篇(一天学会打飞机)
- Java [Leetcode 96]Unique Binary Search Trees
- RxJava-变换操作
- javaweb-国际化
- 【枚举】Vijos P1012 清帝之惑之雍正
- Android view中invalidate方法学习小节
- win8.1 如何查看com端口号
- Servlet监听器
- 用ECLIPSE编译RPI QEMU的kernel