《剑指offer》2-替换空格【Java+Python】

替换空格

1. 题目描述

请实现一个函数,将一个字符串中的空格替换成“%20”。

2. 示例

例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

3. 解题思路

此题比较简单

第一种方法:新开一个内存空间,遍历原字符串数组,如果碰到字符为空格,则append %20进新的空间

第二种方法:不开辟新的空间,首先统计空格数量,从而计算出新的空间大大小,从后面往前面移动。

4. Java实现

方法一:新开一个内存空间

// 新开一个内存空间
public class Solution {
    public String replaceSpace(StringBuffer str) {
        //创建一个新的空间
        StringBuffer out = new StringBuffer();
        for (int i = 0; i < str.length(); i++){
            char a = str.charAt(i);
            if (a == ' '){
                out.append("%20");
            }else{
                out.append(a);
            }
        }
        return out.toString();
     
    }
}

方法二:不开辟新的空间,从后面往前面移动

public class Solution {
    public String replaceSpace(StringBuffer str) {
     // 计算空格的数量
        int spaceNum = 0;
        for (int i = 0; i < str.length(); i++){
            char a = str.charAt(i);
            if (a == ' '){
                spaceNum ++;
            }
        }
        
        // 开辟空间
        int oldIndex = str.length()-1; // 原字符串的下标
        int newLength = str.length() + spaceNum * 2;
        int newIndex = newLength -1;
        str.setLength(newLength); // 重新设置字符串的长度
        
        while(newIndex >= 0){
            if (str.charAt(oldIndex) != ' '){
                str.setCharAt(newIndex, str.charAt(oldIndex));
                oldIndex --;
                newIndex --;
            }else{
                str.setCharAt(newIndex--, '0');
                str.setCharAt(newIndex--, '2');
                str.setCharAt(newIndex--, '%');
                oldIndex--; // 只进行一次减 1
            }
        }
        
        return str.toString();
        
        
    }
}

5. Python实现

方法一:下列的字符串是 不可变对象,使用 + 操作时,会产生许多的对象,所以最好使用第二种方法

class Solution():
    
    def replaceSpace(self, s):
        if type(s) != str:
            return 
        new_s = ''
        for sr in s:
            if sr == ' ':
                new_s += '%20'
            else:
                new_s += sr 
        return new_s 
so = Solution()
s = ' ab c d e '
print(so.replaceSpace(s))
# %20ab%20c%20d%20e%20
print(s.replace(' ', '%20'))

方法二:转换成列表形式

class Solution:
    def replaceSpace(self, s):
        if type(s) != str:
            return
        li = list(s)
        for i in range(len(li)):
            if li[i] == ' ':
                li[i] = '%20'
        res = "".join(li)
        return res
so = Solution()
s = ' ab c d e '
print(so.replaceSpace(s))

如果您觉得本文有用,请点个“在看”

image.png

原文地址:https://www.cnblogs.com/junge-mike/p/13509456.html