翻转字符串
来源:互联网 发布:泰牛程序员怎么样 编辑:程序博客网 时间:2024/05/16 15:27
/** * Created by lxw, liwei4939@126.com on 2017/10/31. * 翻转字符串 */public class reverseString { public void rotateWord(char[] chas){ if(chas == null || chas.length == 0){ return; } reverse(chas, 0, chas.length - 1); int l = -1; int r =-1; for (int i =0; i < chas.length; i++){ if(chas[i] != ' '){ l = i == 0 ||chas[i-1] == ' ' ? i : l; r = i == chas.length -1 || chas[i+1] == ' ' ? i : r; } if(l != ' ' && r != ' '){ reverse(chas, l, r); l = -1; r = -1; } } } public void reverse(char[] chas, int start, int end){ char tmp = 0; while (start < end){ tmp = chas[start]; chas[start] = chas[end]; chas[end] = tmp; start++; end--; } } public void rotate1(char[] chas, int size){ if(chas == null || size <= 0 || size >= chas.length){ return; } reverse(chas, 0, size - 1); reverse(chas, size, chas.length - 1); reverse(chas, 0, chas.length -1); } public void rotate2(char[] chas, int size){ if(chas == null || size <= 0 || size >= chas.length){ return; } int start = 0; int end = chas.length - 1; int lpart = size; int rpart = chas.length - size; int s = Math.min(lpart, rpart); int d = lpart - rpart; while (true){ exchange(chas, start, end, s); if(d == 0){ break; } else if(d > 0){ start += s; lpart = d; } else { end -= s; rpart = -d; } s = Math.min(lpart, rpart); d = lpart - rpart; } } public void exchange(char[] chas, int start, int end, int size){ int i = end - size + 1; char tmp = 0; while (size-- != 0){ tmp = chas[start]; chas[start] = chas[i]; chas[i] = tmp; start++; i++; } } public static void main(String[] args){ reverseString obj = new reverseString(); String str = "1234567ABCD"; char[] arrStr = str.toCharArray(); int size = 7; obj.rotate2(arrStr, size); System.out.println(arrStr); }}
阅读全文
0 0
- 翻转字符串
- 翻转字符串
- 字符串翻转
- 字符串翻转
- 翻转字符串
- 翻转字符串
- 字符串翻转
- 翻转字符串
- 翻转字符串
- 字符串翻转
- 翻转字符串
- 字符串翻转
- 翻转字符串
- 字符串翻转
- 翻转字符串
- 字符串翻转
- 字符串翻转
- 字符串翻转
- Oracle中执行存储过程call和exec区别
- sumbit text3的设置
- 时间选择器
- 有限背包计数问题 (分类dp)
- VC 如何在一个矩形框中居中显示一个长字符串
- 翻转字符串
- 关于ARM架构下ucos2任务切换函数OSCtxSw源码分析
- 【转载】用“人话”解释不精确线搜索中的Armijo-Goldstein准则及Wolfe-Powell准则
- 数位DP入门后部分题解
- HTTPS原理
- ElasticSearch学习36_Elasticsearch扩展性插件
- HDU 4407 Sum(容斥)
- 杭电2036叉乘法求多边行面积
- 笨办法学Python-习题0 准备工作