Leetcode剑指 Offer 05. 替换空格

  • 题目要求

Leetcode剑指 Offer 05. 替换空格_第1张图片

  • 思路:

    • 遍历字符串,遇到空格替换
    • 因为字符串s长度可变,所以使用的是while循环,实时更新字符串的长度
  • 完整代码:
class Solution:
    def replaceSpace(self, s: str) -> str:
        cur, lenth = 0, len(s)
        while cur < lenth:
            if s[cur] == " ":
                s = s[:cur] + "%20" + s[cur + 1:]
            cur += 1
            lenth = len(s)
        return s

你可能感兴趣的:(leetcode,python)