TypechoJoeTheme

IT技术分享

统计

[LintCode 212] Space Replacement [C++] [Runtime : 10MS]

2017-07-21
/
0 评论
/
612 阅读
/
正在检测是否收录...
07/21

1. Description

Write a method to replace all spaces in a string with %20. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string.

You code should also return the new length of the string after replacement.

2. Example

Given "Mr John Smith", length = 13.
The string after replacement should be "Mr%20John%20Smith", you need to change the string in-place and return the new length 17.

3. Code

int replaceBlank(char string[], int length)
{
    if (string == NULL) {
        return 0;
    }

    int spaceCount = 0;

    for (int i = 0; i < length; i++) {
        if (string[i] == ' ') {
            spaceCount++;
        }
    }

    int len = length + (spaceCount << 1);

    int right = len - 1;
    for (int i = length - 1; i >= 0; i--) {
        if (string[i] != ' ') {
            string[right--] = string[i];
        }
        else {
            string[right--] = '0';
            string[right--] = '2';
            string[right--] = '%';
        }
    }
    return len;
}

4.Test

#include <stdio.h>

using namespace std;

class LintCode0212 {
public:
    int replaceBlank(char string[], int length)
    {
        if (string == NULL) {
            return 0;
        }

        int spaceCount = 0;

        for (int i = 0; i < length; i++) {
            if (string[i] == ' ') {
                spaceCount++;
            }
        }

        int len = length + (spaceCount << 1);

        int right = len - 1;
        for (int i = length - 1; i >= 0; i--) {
            if (string[i] != ' ') {
                string[right--] = string[i];
            }
            else {
                string[right--] = '0';
                string[right--] = '2';
                string[right--] = '%';
            }
        }
        return len;
    }
};

int main()
{
    LintCode0212 lintcode;
    char string[] = { 'M', 'r', ' ', 'J', 'o', 'h', 'n', ' ', 'S', 'm', 'i', 't', 'h', '\0' };
    printf("%d", lintcode.replaceBlank(string, 13));
    return 0;
}
Array
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/598/(转载时请注明本文出处及文章链接)