字符串
面试题5:替换空格
题目描述:请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
详细代码:
class Solution:
# s 源字符串
def replaceSpace(self, s):
# write code here
s = list(s)
count = 0
for e in s:
if e == ' ':
count += 1
if count != 0:
p1 = len(s)-1
s += [None] * (2 * count)
p2 = len(s)-1
while p1 >= 0:
if s[p1] == ' ':
for i in ['0', '2', '%']:
s[p2] = i
p2 -= 1
else:
s[p2] = s[p1]
p2 -=1
p1 -= 1
return ''.join(s) #不能使用str(),这样不会把字符拼接起来
链表
面试题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
if not listNode :
return []
res = []
while lisNode.next is not None:
res.append(listNode.val)
listNode = listNode.next
res.append(listNode.val)
return res[::-1]