劍指offer2:替換空格

在這裏插入圖片描述

思想

  1. 使用字符串內置函數replace直接替換,這樣雖然方便,但是我們並不知道它的算法時間複雜度,儘管他很快。
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        
        return s.replace(" ","%20")

在這裏插入圖片描述

  1. 從一般性考慮,就是在不知道有這個內置函數的時候
# 方法二:從C語言的角度考慮
# -*- coding:utf-8 -*-
class Solution:
    # s 源字符串
    def replaceSpace(self, s):
        # write code here
        string = ""
        strLen = len(s)
        for i range(strLen):
            if s[i] == " ":
                string += "%20"
            else:
                string += s[i]
        return string
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章