牛客-剑指offer第2版-Python编程(5,6题)

    xiaoxiao2022-07-04  112

    5、替换空格(字符串)

    请实现一个函数,将一个字符串中的每个空格替换成“ ”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We Are Happy。

     

    # -*- coding:utf-8 -*- class Solution: # s 源字符串 def replaceSpace(self, s): # write code here if not isinstance(s,str) or len(s) <= 0 or s == None: return "" #遍历求字符串中的空格数 spaceNum = 0 for i in s: if i == " ": spaceNum += 1 #newStrLen为把空格替换后的长度 newStrLen = len(s) + spaceNum * 2 newStr = newStrLen * [None] #双指针:Origin和New indexOfOriginal, indexOfNew = len(s) - 1, newStrLen - 1 while indexOfNew >= 0 and indexOfNew >= indexOfOriginal: if s[indexOfOriginal] == ' ': newStr[indexOfNew-2:indexOfNew+1] = ['%', '2', '0'] indexOfNew -= 3 indexOfOriginal -= 1 else: newStr[indexOfNew] = s[indexOfOriginal] indexOfNew -= 1 indexOfOriginal -= 1 return "".join(newStr)

     

    6、从尾到头打印链表(链表)

    输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

     

    # -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, listNode): # write code here stack = list() while listNode: stack.append(listNode.val) listNode = listNode.next return stack[::-1]

     

    最新回复(0)