博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
2替换空格
阅读量:4322 次
发布时间:2019-06-06

本文共 1930 字,大约阅读时间需要 6 分钟。

题目描述

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
 
记忆:找到空格数量,找到copy后最后一个字符的位置,然后使用一个for循环,中间ij变量,分为有空格和无空格的拷贝。记住需要对str变量进行copy一份,在统计空格。
class Solution {public:    void replaceSpace(char *str,int length) {        if(str == nullptr || length < 0){            return;        }        int oldLen = strlen(str),newLen = 0;        int spaceNum = 0;        char* idx = str;        while(*idx != '\0'){            if(*idx == ' '){                ++spaceNum;            }            ++idx;        }        newLen = oldLen + 2 * spaceNum;        if(newLen > length){            return;        }        for(int i= oldLen,j = newLen;i >= 0 && j >= 0;--i,--j){            if(str[i] == ' '){                str[j] = '0';                str[j - 1] = '2';                str[j - 2] = '%';                j = j  - 2;            }            else{                str[j] = str[i];            }        }        return;    }};

 

 

变式题:

有两个排序的数组A和B,内存在A的末尾有足够多的空余空间容纳B,请实现一个函数,把B中的所有数字都插入到A中并且所有的数字是有序的。

#include
#include
using namespace std;#define N 20#define M 2void func(vector
&a,vector
&b) { if (a.size() == 0) { return; } int totalSize = 2 * M - 1; int i = M - 1, j = M - 1; for (i,j; i >= 0 && j >= 0;) { if (a[i] > b[j]) { a[totalSize] = a[i--]; } else { a[totalSize] = b[j--]; } --totalSize; } if (j >= 0) { for (int k = 0; k <= j; ++k) { a[k] = b[k]; } }}int main() { vector
a(N, 0); vector
b(M, 0); for (int i = 0; i < M; ++i) { a[i] = i; b[i] = i + 2; } func(a, b); for (int i = 0; i < 2 * M; ++i) { cout << a[i] << " "; } cout << endl; system("pause");}

 

转载于:https://www.cnblogs.com/dingxiaoqiang/p/7868416.html

你可能感兴趣的文章
SecureCRT的安装
查看>>
POJ2635-The Embarrassed Cryptographer
查看>>
css中font-family的中文字体
查看>>
学习笔记:CentOS 7学习之十二:查找命令
查看>>
delphi回调函数
查看>>
收到了TUSC寄来的V$ View For Oracle Database 11g
查看>>
gc buffer busy/gcs log flush sync与log file sync
查看>>
Java String.intern的深入研究
查看>>
动态上下线集群详解
查看>>
帝国cms修改栏目后文章列表的url错误怎么解决
查看>>
Linux下查看用户列表
查看>>
字符串左旋转操作
查看>>
PyQt5发布技巧:指定插件(plugins)路径
查看>>
centos 6.6编译安装nginx
查看>>
http接口调用
查看>>
进入OS前的两步之PendSV(任务切换)
查看>>
using-ef-code-first-with-an-existing-database
查看>>
关于h5页面内嵌到andriod时的webview在设置缩放问题
查看>>
echarts中间有字饼图Demo1
查看>>
java泛型的理解
查看>>