重组字符串
来源:互联网 发布:seo引擎搜索 编辑:程序博客网 时间:2024/04/29 00:48
在面试过程中遇到的这个问题。
对于输入:***a*b*cd**e*....
期望输出:********abcde....
要求:将字符串中的*全部移动到前半部分,字母移动到后半部分,并保持顺序不变
思路1:定义两个StringBuilder,遍历输入,如果是*存入第一个StringBuilder,否则存入第二个StringBuilder。最后拼接两个字符串。时间复杂度0(N),空间复杂度O(n)。代码实现如下:
/** * 重组字符串:****a*c*d**e*fgh.... * @Date:2015-3-12 * @author renxiao * @param s * @return */public static String resort(char[] input){StringBuilder left=new StringBuilder();StringBuilder right=new StringBuilder(); for (int i = 0; i < input.length; i++) {if(input[i]=='*'){left.append(input[i]);}else {right.append(input[i]);}}return left.append(right).toString();}
思路2:从后往前扫描,一边计算*号个数,一边将其它字符置于此时*号数量之后位置,最后填补*号。这样不需要额外的空间就能完成。因为元素只需遍历一次,且覆盖的是遍历过的元素。时间复杂度O(n),空间复杂度0.
代码如下:
/** * @Date:2015-3-12 * @author renxiao * @param input * @return */public static char[] resort(char[] input){ int mark = input.length - 1; int asteriskNum = 0; for( ; mark >= 0 ; mark--){ char c = input[mark]; if(c != '*'){ input[mark + asteriskNum] = c; }else{ asteriskNum++; } } for( int i = 0 ; i < asteriskNum ; i++){ input[i] = '*'; } return input;}
今天刷题目的时候,在leetcode上遇到了和本题相似的一个题
题号:27 题目
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Array Two Pointers这里采用从前往后遍历,同时记录需要移除元素的个数,由于这里只需要返回剩余元素的个数,所以不用再将后半部分进行赋值了,只需要返回数组长度即可。
具体的代码如下:
/** * @Date:2013-03-13 * @author:renxiao * */public class Solution { public int removeElement(int[] A, int elem) { int numEle=0; for(int i=0;i<A.length;i++){ if(A[i]==elem){ numEle++; } else{ A[i-numEle]=A[i]; } } return A.length-numEle; }}
0 0
- 字符串重组
- 重组字符串
- 字符串重组
- 截取重组字符串
- string.Join 重组字符串
- 前后重组字符串
- 算法之字符串重组
- [小米]字符串重组
- 小米面试题 :字符串重组
- AngularJS分割重组字符串
- js 给字符串切片重组
- c语言重组字符串问题
- 51Nod-1638-字符串重组
- 重组
- 重组
- 重组
- 重组
- 重组
- stm32 复用时钟开启情况
- 什么是负载,什么是网站负载,什么是网站负载均衡?
- 晋朝那些事儿
- GCD中常用函数及释义
- ThinkPHP模板多层继承
- 重组字符串
- 清华大学教室说明
- Activity复用的时候接受不到Intent数据的原因以及解决方法
- WPF中StringFormat的用法
- 避免图像去雾算法中让天空部分出现过增强的一种简易方法
- 刘未鹏博客精华整理55条
- watch命令及lipo
- memcached源码分析-----get命令处理流程
- Android中的广播机制