题目:http://www.lintcode.com/en/problem/space-replacement/
思路:
- 计算空格
- 创建一个新的string,长度为原先长度+2*空格数
- 用新string从后面还是加入char,如果空格则替换成%20
public int replaceBlank(char[] string, int length) {
// write your code here
int index =0;
int space =0;
for(int i=0;i<length;i++){
if(string[i] == ' '){
space ++;
}
}
index = space + space + length;
char[] newstring = new char[index];
for(int i=length -1;i>=0;i--){
if(string[i] == ' '){
newstring[index-1] = '0';
newstring[index-2] = '2';
newstring[index-3] = '%';
index = index -3;
}
else{
newstring[index-1] = string[i];
index --;
}
}
int newlength = newstring.length;
return newlength;
}
微信扫一扫
支付宝扫一扫