替换空格 概述:请实现一个函数,把字符串 s 中的每个空格替换成 "%20" 。 输入:s = "We are happy." 输出:"We%20are%20happy." 方法一:暴力循环 思路:在 Python 和 Java 等语言中,string 都被设计成「不可变」的类型,即无法直接修改字符串的某一位字符,只读不写,需要新建一个字符串实现。 # 暴力循环 class Solution: def replaceSpace(self, s: str) -> str: s_new = '' # 也可以用[].append,然后join成str for i in s: if i == ' ': s_new += '%20' else: s_new += i return s_new 方法二:replace函数 思路:直接用 replace 内置函数,需要注意 replace 不会改变原 string 的内容。 # replace函数 class Solution: def replaceSpace(self, s: str) -> str: s = s.replace(' ', '%20') return s 总结 不可变类型,绑定地址,只读不写!