Question
设计一种方法,将一个字符串中的所有空格替换成 %20 。你可以假设该字符串有足够的空间来加入新的字符,且你得到的是“真实的”字符长度。
Solution 1
需要额外的一个数组:
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(string == NULL || length < 0)
return -1;
int ans = length;
char tmp[1000];
memcpy(tmp, string, ans);
for(int i = 0; i < ans; i ++)
{
if(string[i] == ‘ ‘)
{
for(int j = i + 1; j < ans; j ++)
{
string[j + 2] = tmp[j];
}
string[i] = ‘%‘;
string[i + 1] = ‘2‘;
string[i + 2 ] = ‘0‘;
ans += 2;
i += 2;
memcpy(tmp, string, ans);
}
}
return ans;
}
};
Solution 2
不需要额外的空间,直接在原数组里操作:
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(string == NULL || length < 0)
return -1;
int blank_num = 0;
for(int i = 0; i < length; i ++)
{
if(string[i] == ‘ ‘)
blank_num += 1;
}
int new_length = length + blank_num * 2;
int index_new = new_length;
int index_ori = length;
while(index_ori >= 0 && index_new > index_ori )
{
if(string[index_ori] == ‘ ‘)
{
string[index_new--] = ‘0‘;
string[index_new--] = ‘2‘;
string[index_new--] = ‘%‘;
}
else
string[index_new--] = string[index_ori];
index_ori -= 1;
}
return new_length;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-21 05:13:45