面试题05

请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

示例 1:

输入:s = "We are happy."
输出:"We%20are%20happy."

限制:

  • 0 <= s 的长度 <= 10000

Solutions

  1. straight forward

char* replaceSpace(char* s){
    int len = 0;
    const char * r = s;
    while (*r)
        len += (*r++ == ' ' ? 3 : 1);

    char * w = (char *) malloc((len + 1) * sizeof(char));
    char * res = w;
    while (*s) {
        if (*s++ != ' ')
            *w++ = *(s - 1);
        else {
            *w++ = '%';
            *w++ = '2';
            *w++ = '0';
        }
    }
    *w = '\0';

    return res;
}

or

class Solution {
public:
    string replaceSpace(string s) {
        string res;
        for (auto c : s)
            if (c == ' ')
                res += "%20";
            else
                res += c;
        return res;
    }
};

Last updated

Was this helpful?