剑指offer 04 替换空格

来源:互联网 发布:中国邮政数据传媒中心 编辑:程序博客网 时间:2024/06/06 14:24

题目描述

请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:
水题!
1.另外开辟一个字符串new_s,遍历s,把s赋值给new_s。空间复杂度O(n)。
2.两个指针。
代码1:
class Solution:    # s 源字符串    def replaceSpace(self, s):        res = ''        for i in s:            if i == ' ':                res += '%20'            else:                res += i        return res

代码2:
class Solution {public:void replaceSpace(char *str,int length) {         //统计空格个数        int spaceCount = 0;        int i = 0;        for (i = 0; i < length; i ++){            if(str[i] == ' ')                spaceCount ++;        }        int newLength = length + spaceCount * 2;//新长度        int leftindex = length - 1;        int rightindex = newLength - 1;        while(leftindex >= 0){            if(str[leftindex--] == ' '){                str[rightindex--] = '0';                str[rightindex--] = '2';                str[rightindex--] = '%';            }else{                str[rightindex--] = str[leftindex + 1];            }        }}};


原创粉丝点击