您的位置:首页 > 其它

Space Replacement

2015-11-28 20:44 260 查看
Write a method to replace all spaces in a string with %20. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string.

You code should also return the new length of the string after replacement.

Example

Given “Mr John Smith”, length = 13.

The string after replacement should be “Mr%20John%20Smith”.

分析

原地算法 从后往前遍历

public class Solution {
/**
* @param string: An array of Char
* @param length: The true length of the string
* @return: The true length of new string
*/
public int replaceBlank(char[] string, int length) {
// Write your code here
if(string ==null)return 0;

int space =0;
for(char c: string ){
if(c==' ')space++;
}
int r = length +2*space -1;
for(int i = length -1;i>=0;i--){
if(string[i]!=' '){
string[r]=string[i];
r--;
}else{
string[r--]='0';
string[r--]='2';
string[r--]='%';
}
}
return length+2*space;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string