您的位置:首页 > Web前端

剑指offer---替换空格(4)

2017-11-25 17:40 274 查看
题目:请实现一个函数,把字符串中的每个空格替换成”%20”,例如输入“we are happy”,则输出we%20are%20happy.

时间复杂度为:O(n)

#include <iostream>
#include <string>
using namespace std;

//如果字符串的空间不足,则需要重新开辟一个空间来进行处理,这样就比较简单,时间复杂度为O(n)
//在此讨论原有字符串的长度足够,且要求在原有字符串上改动
void ReplaceBlack(char *str)
{
int len = strlen(str);//字符串原来的长度
int newlen = len;
char* flg = str;
while(*flg != '\0')
{
if(*(flg++) == ' ')
{
newlen+=2;
}
}
while(len >= 0 && newlen > len)
{
if(str[len] == ' ')
{
str[newlen--] = '0';
str[newlen--] = '2';
str[newlen--] = '%';
}
else
{
str[newlen--] = str[len];
}
len--;
}
}
int main()
{
char arr[128] = "we are happy";
ReplaceBlack(arr);
cout<<arr<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息