天天看点

剑指OFFER-替换空格QuestionSolution

剑指OFFER-替换空格

  • Question
  • Solution
    • 原字符串替换

Question

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

关键词:字符串 替换

Solution

原字符串替换

从前往后计算空格数,从后往前替换空格,保证每个字符只移动一次。

时间复杂度: O(N)

空间复杂度:O(1)

  • Python
## Python中String类型不可改变数值,只能拼接
def replaceSpace(self, s):
    count = 0
    l = len(s)
    for a in s:
        if a==' ':
            count += 1
            s += '  '
    for i in range(l-1, -1, -1):
        if s[i] != ' ':
            s = s[:i+count*2] + s[i] + s[i+count*2+1:]
        else:
            count -= 1
            s = s[:i+count*2] + '%20' + s[i+count*2+3:]
    return s
           
  • C++
void replaceSpace(char *str,int length) {
        int count = 0;
        for(int i=0; i< length; i++){
            if (str[i]==' ')
                count++;
        };
        for(int i=length-1; i>=0; i--){
            if(str[i]==' '){
                count--;
                str[i+count*2] = '%';
                str[i+count*2+1] = '2';
                str[i+count*2+2] = '0';
            }
            else
                str[i+count*2] = str[i];
        };
	}