5.スペースを置き換える

質問:文字列のスペースを「%20」に置き換える関数を実装してください。たとえば、文字列がWe Are Happyの場合、置換後の文字列はWe%20Are%20Happyです。

時間の複雑さはO(n)です。
class solution(object):
    def replace_space(self, string):
        num_space = 0
        for x in string:
            if x == ' ':
                num_space += 1
        new_lenth = len(string) + 2 * num_space
        index_orange = len(string) - 1
        index_new = new_lenth - 1
        new_string = [None for x in range(new_lenth)]
        while index_orange >= 0 :
            if string[index_orange] == ' ':
                new_string[index_new] = '0'
                index_new -= 1
                new_string[index_new] = '2'
                index_new -= 1
                new_string[index_new] = '%'
                index_new -= 1
            else:
                new_string[index_new] = string[index_orange]
                index_new -= 1
            index_orange -= 1
        return ''.join(new_string)

#ここでは、時間にスペースを使用してストレージスペースを開き、リストを保存するためのスペースを '%20'に置き換えるという考え方を使用しています 元の文字列は文字列であり、新しい文字列は最初にリストを使用して文字列に変換されることに注意してください

時間の複雑さはO(n2)です。
方法1:

クラスソリューション(オブジェクト):
def replace_space(self、string):
return '%20'.join(string.split(' '))
#巧妙にPythonのメソッドを使用して、文字列を直接分割してつなぎ合わせることができる

方法2(別の改良バージョン、コードロジックは変更されておらず、より直感的):
def replace_space(string):
    count = 0
    for x in string:
        if x==' ':
            count+=3
        else:
            count +=1
    p1 ,p2= len(string)-1,count-1
    newString = [None for x in range(count)]
    while p1>=0 and p2>=0:
        if string[p1]==' ':
            newString[p2] = '0'
            newString[p2-1] = '2'
            newString[p2-2] = '%'
            p2-=3
            p1-=1
        else:
            newString[p2]=string[p1]
            p1-=1
            p2-=1
    return ''.join(newString)
a= 'We are happy.'
print(replace_space(a))
元の記事を16件公開 Likes0 訪問数161

おすすめ

転載: blog.csdn.net/qq_43275748/article/details/102641332