Please enable Javascript to view the contents

剑指office(二)替换空格

 ·  ☕ 2 分钟  ·  🎅 YSL

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

示例1

输入

"We Are Happy"

返回值

"We%20Are%20Happy"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return string字符串
     */
    string replaceSpace(string s) {
        for(int i = 0;i<s.size();i++)
        {
            if(s[i]==' ')
            {
                s = s.replace(i,1,"%20");
            }
        }
        return s;
    }
};

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return string字符串
     */
    string replaceSpace(string s) {
        string newS;
        for(int i = 0;i<s.size();i++)
        {
            if(s[i]==' ')
            {
                newS +="%20"; 
            }else
            {
                newS +=s[i];
            }
        }
        return newS;
    }
};

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return string字符串
     */
    string replaceSpace(string s) {
        int sSize = s.size();
        int spaceNum = 0;
        for(int i = 0;i<sSize;i++)
        {
            if(s[i]==' ')
            {
                spaceNum++;
            }
        }
        int newLen = spaceNum*2 + sSize;
        int newI = 0;
        string newS(newLen,' ');
        for(int i = sSize - 1,newI = newLen-1;i>=0;i--,newI--)
        {
            if(s[i]==' ')
            {
                newS[newI] = '0';
                newI = newI-1;
                newS[newI] = '2';
                newI = newI -1;
                newS[newI] = '%';
            }
            else
            {
                newS[newI] = s[i];   
            }
        }
        return newS;
    }
};