您的位置:首页 > Web前端

剑指offer----005(字符串空格替换)

2018-01-19 14:24 405 查看
更多题目请点链接:《剑指offer》目录索引

问题描述:

实现一个函数,将字符串中的每个空格替换成%20。例如:”We are

hanppy.“,则输出“We%20are%20happy.”,要求时间复杂度为O(n)

问题分析:

根据描述,此题意思改变字符串内容,并且改变了原字符串长度;

要求时间复杂度为0(n),故不能直接替换;

思路:

第一步,求空格数:要知道改变字符串后的长度,需知道原字符串中空格数,才能确定替换后的字符串长度;

第二步,替换空格:将空格替换成字符串”%20”,替换时,从后往前遍历,遇到空格进行替换,这样做的好处是,可保证原字符串的完整性,不会覆盖原来的字符串(如图)



具体代码:

void StringReplace(char* dst, int len)
{
assert(dst);
assert(len>0);

int count = 0,  i = 0;

while (dst[i] != '\0')
{
if (dst[i] == ' ')
{
++count;
}
++i;
}

int  index = length ;//原字符串的尾
int newindex = length + count * 2;//新字符串的长度

if (newindex  < length)
{
return;
}

while (index>=0 && newindex>=0)
{
if (dst[index] != ' ')
{
dst[newindex--] = dst[index];
}
else
{
dst[newindex--] = '0';
dst[newindex--] = '2';
dst[newindex--] = '%';
}

index--;
}

}


测试用例:

void Test()
{

char arr[30] = "We are happy.";
int len = strlen(arr);

printf("%s\n", arr);

StringReplace(arr, len);

printf("%s\n",arr);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐