题目地址:
https://www.lintcode.com/problem/space-replacement/description
给定一个字符串,要求将其所有的空格替换为 ,要in-place做。可以先算出替换后的字符串长度,然后再从后向前填写字符串。代码如下:
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
// 计算替换后的字符串长度
int len = 0;
for (int i = 0; i < length; i++) {
len += string[i] == ' ' ? 3 : 1;
}
for (int i = len - 1; i >= 0; i--, length--) {
// 如果不等于空格,则直接覆盖,否则依次覆盖'0','2'还有'%'
if (string[length - 1] != ' ') {
string[i] = string[length - 1];
} else {
string[i--] = '0';
string[i--] = '2';
string[i] = '%';
}
}
return len;
}
}
时间复杂度 。