【程序员面试金典】01.03. URL化

1.题目

URL化。编写一种方法,将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java实现的话,请使用字符数组实现,以便直接在数组上操作。)

示例1:

 输入:"Mr John Smith    ", 13
 输出:"Mr%20John%20Smith"
示例2:

 输入:"               ", 5
 输出:"%20%20%20%20%20"
提示:

字符串长度在[0, 500000]范围内。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/string-to-url-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2.题解

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

下面的快,但是感觉像是个傻子!水题直接过吧!

class Solution {
public:
    string replaceSpaces(string S, int length) {
        if (S.empty()) return S;
        int cnt = 0;
        for (int i = 0; i < length; ++i) {
            if (S[i] == ' ') ++cnt;
        }
        int newLen = length + cnt * 2, j = newLen - 1;
        for (int i = length - 1; i >= 0 && i != j; --i) {
            if (S[i] == ' ') {
                S[j--] = '0';
                S[j--] = '2';
                S[j--] = '%';
            } else {
                S[j--] = S[i];
            }
        }
        S[newLen] = '\0';
        return S;
    }
};

引用:https://leetcode-cn.com/problems/string-to-url-lcci/solution/mian-shi-ti-0103-urlhua-jian-dan-shuang-zhi-zhen-b/

发布了13 篇原创文章 · 获赞 4 · 访问量 539

猜你喜欢

转载自blog.csdn.net/weixin_44556968/article/details/105417451