面试题 01.03. String to URL LCCI

Problem

Write a method to replace all spaces in a string with ‘%20’. You may assume that the string has sufficient space at the end to hold the additional characters,and that you are given the “true” length of the string. (Note: If implementing in Java,please use a character array so that you can perform this operation in place.)

Example1

Input: "Mr John Smith ", 13
Output: “Mr%20John%20Smith”

Example2

Input: " ", 5
Output: “%20%20%20%20%20”

Solution

class Solution {
public:
    string replaceSpaces(string S, int length) {
        string ret = "";
        if(length == 0)
            return ret;
        for(int i = 0;i<length;++i)
        {
            if(S[i] == ' ')
            {
                ret += "%20";
            }
            else
            {
                ret += S[i];
            }
        }

        return ret;

    }
};
发布了526 篇原创文章 · 获赞 215 · 访问量 54万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/105084482