Replace all spaces in string with ' ' (Cracking the Code Interview)
来源:互联网 发布:html5 360全景源码 编辑:程序博客网 时间:2024/06/05 18:04
Write a method to replace all spaces in string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place).
Solustion:
Edit the string from backward.
(1) 1st scan: count how many spaces. Then we know how long the final string.
(2) 2st scan: edit string from end. When we see a space, copy "%20" into the next spots. If it's not space, we copy the original character.
public class Unique {public static void main(String arg[]){char[] ch=new char[30];ch[0]='a';ch[1]='b';ch[2]=' ';ch[3]=' ';ch[4]='c';trans(ch, 5);}public static void trans(char[] ch, int length){int spaceCount=0,newLength=0;for(int i=0;i<length;i++){if(ch[i]==' ') spaceCount++;}newLength=length+2*spaceCount;int outputLength=newLength;ch[newLength]='\0';for(int i=length-1;i>0;i--){if(ch[i]==' '){ch[newLength-1]='0';ch[newLength-2]='2';ch[newLength-3]='%';newLength=newLength-3;}else{ch[newLength-1]=ch[i];newLength--;}} for(int i=0;i<outputLength;i++){System.out.println(ch[i]);}}}
The result:
0 0
- Replace all spaces in string with ' ' (Cracking the Code Interview)
- 【5】Replace all spaces in a string with ‘%20’
- Write a method to replace all spaces in a string with ‘%20’.
- Write a method to replace all spaces in a string with ‘%20’
- Ch1-5: Write a method to replace all spaces in a string with ‘%20’.
- Q1.4 Write a method to replace all spaces in a string with ‘%20’.
- Cracking the code interview总结
- cracking the code interview problem 1.1
- cracking the code interview problem 1.3
- cracking the code interview balanced tree python
- cracking the code interview LCA Python
- cracking code interview
- Cracking the code interview 面试题:两个数相加
- Cracking the Code Interview (1): 跟踪数组的中位数
- 笔记摘录——Cracking the code interview
- cracking the code interview convert array to BST Python
- Cracking the Code Interview Chapter One-- TaylorZhangYuxin's Solusion
- Cracking the Code Interview Chapter Two-- TaylorZhangYuxin's Solusion
- 阿飞阿飞,你要保重身体啊!
- UVA 409 Excuse
- 如何从 GRUB rescue 恢复 Win7,win7 USB恢复盘制作
- 关于内核进程对象的存活期问题。
- 全排列算法的实现
- Replace all spaces in string with ' ' (Cracking the Code Interview)
- 关于页面优化,js优化、css优化策略
- Java面向对象——继承
- 关于Android横竖屏布局
- 思考c++中rand()函数产生随机数需不需要srand()的发现
- Frenquency == 4
- 电感 电容耦合的判断
- Remove Element
- Collection Iterator