1:题目
title: 面试题05 替换空格
introduction:
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = “We are happy.”
输出:“We%20are%20happy.”
限制:
0 <= s 的长度 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof
2:python实现
2.1:思路1
2.1.1:代码
class Solution:
def replaceSpace(self, s: str) -> str:
i = 0
while i < len(s):
if s[i] == ' ':
s = s[: i] + "%20" + s[i+1:]
i += 3
continue
i += 1
return s
if __name__ == '__main__':
S = "MWe are happy."
Sol = Solution()
S = Sol.replaceSpace(S)
print(S)
2.1.2:分析
利用循环,每一次判断改字符是否为‘ ’,当为True当时候,利用python当切变和字符串相加操作,将“%20”加入进去,并同时将循环索引加3,同时S当长度会自动加3.
注意:刚开始想过用python当replace,但是毕竟这是题,用replace什么也考察不到,所以用了这个思路,并且觉得这个思路可能不是最优解,后续研究后会更新。