2替换空格

题目描述

请实现一个函数,将一个字符串中的空格替换成“%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 != ''){
            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<iostream>
#include<vector>
using namespace std;
#define N 20
#define M 2
void func(vector<int> &a,vector<int> &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<int> a(N, 0);
    vector<int> 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