替换字符串中的空格为$$$。要求时间复杂度为O(N)

来源:互联网 发布:图像清晰度检测算法 编辑:程序博客网 时间:2024/05/16 17:55

替换字符串中的值,如果是一个换一个,那么我们在遍历的时候就恶意直接替换,以为没有多余空间的使用,但是现在要将一个空格,换为三个‘ON’,那么在空间的开销上,自然会比之前多2*空格个数,然后从后往前依次存放相应的值。

#define _CRT_SECURE_NO_WARNINGS 10#include<iostream>using namespace std;void replace(char str[],int length){    int i = 0;    int num = 0;    while (str[i] != '\0')    {        if (str[i] == ' ')            num++;        i++;    }    int newlength = length + 2 * num;    if (newlength <= length)        return;    int indexold = length;    int indexnew = newlength;    while (indexold >= 0 && indexnew>indexold)    {        if (str[indexold] == ' ')        {            str[indexnew--] = '$';            str[indexnew--] = '$';            str[indexnew--] = '$';        }        else            str[indexnew--]=str[indexold];        indexold--;    }    printf("%s\n", str);}int main(){    char str[100] = "talk is cheap show me the code";    int len = strlen(str);    replace(str,len);    system("pause");    return 0;}
阅读全文
0 0
原创粉丝点击