您的位置:首页 > 其它

[LintCode] 空格替换

2015-06-29 23:59 218 查看
class Solution {
public:
/**
* @param string: An array of Char
* @param length: The true length of the string
* @return: The true length of new string
*/
int replaceBlank(char string[], int length) {
// Write your code here
if (!length) return 0;
int spaces = 0;
for (int i = 0; string[i]; i++)
if (string[i] == ' ')
spaces++;
if (!spaces) return length;
int newlen = length + spaces * 2;
int pn = newlen - 1, p = length - 1;
while (p >= 0 && pn >= 0) {
if (string[p] == ' ') {
string[pn--] = '0';
string[pn--] = '2';
string[pn--] = '%';
p--;
}
else string[pn--] = string[p--];
}
return newlen;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: