题目描述

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
 
C++使用string,python使用replace都非常简单。
除去上述方法,C++如果在原地址替换需要从后向前替换。
C++:
#include <iostream>
using namespace std;
class Solution {
public:
    void replaceSpace(char * str, int length) {
        // 在str原地址上替换,先遍历空格数量,再从后向前替换(从前向后替换费时费力)
        int n = strlen(str);// 原字符串长度,不包含\0
        int space_num = 0;
        for (int i = 0; i < n; i++) {
            if (str[i] == ' ') {
                space_num++;
            }
        }
        int n_new = n + space_num*2; //一个空格变成三个字符%20
        while ((n>=0)&&(n_new>n))
        {
            cout << str[n] << endl;
            // 从'\0'开始
            if (str[n] == ' ') {
                str[n_new--] = '0';
                str[n_new--] = '2';
                str[n_new--] = '%';
            }
            else {
            
                str[n_new--] = str[n];
            }
            n--;
        }
    }
};


int main()
{
    Solution obj;
    char* str = "hello world";
    int n = strlen(str);// 字符串长度,不包含\0
    obj.replaceSpace(str, n);
    cout << str << endl;
    cin.get();
    cin.get();
    return 0;
}

C++的代码在vs2015会有写入冲突,还是用string比较好不会有这种冲突。。但这段代码在牛客网上是通的……

Python:

# -*- coding:utf-8 -*-
class Solution:
    def replaceSpace(self, s):
        s_new = ""
        n = len(s)
        for i in xrange(n):
            if s[i]==' ':
                s_new += "%20"
            else:
                s_new += s[i]
        return s_new
        
        
if __name__ == '__main__':
    obj = Solution()
    s = "hello world"
    print obj.replaceSpace(s)

在牛客网上测试时间与空间占用:

C++: 3ms,488k

Python:19ms,5728k

 

 

posted on 2018-04-21 21:31  想飞的萌猪  阅读(197)  评论(0编辑  收藏  举报