返回顶部

收藏

o(n)时间复杂度替换字符串中空格为%20

更多
class offer_book:
    def replaceBlank( p_str, rpl_str ):
        blank = ' '
        numOfBlank = 0
        originalLen = len( p_str )
        for char in p_str:
            if char == blank:
                numOfBlank += 1
        originalIndex = originalLen - 1
        newLen = originalLen + numOfBlank * ( len( rpl_str ) - len( blank ) )
        newIndex = newLen - 1
        newStr = [ blank ] * newLen
        while originalIndex >= 0:
            if p_str[ originalIndex ] == blank:
                newStr[ newIndex ] = '0'
                newIndex -= 1
                newStr[ newIndex ] = '2'
                newIndex -= 1
                newStr[ newIndex ] = '%'
                newIndex -= 1
            else:
                newStr[ newIndex ] = p_str[ originalIndex ]
                newIndex -= 1
            originalIndex -= 1
        return str( newStr )

newStr = offer_book.replaceBlank( ' we are happy! ', '%20' )
print( newStr )

标签:python

收藏

0人收藏

支持

0

反对

0

发表评论