Day2
简单题
用2个栈实现队列
我的做法
是只用了一个栈
相当于就是一个队列。。
删除,用到的是python的切片,从第一个往后切,时间复杂度应该是O(n)吧,空间复杂度是O(n)
返回当然是第一个元素
这样好像不是题目的意思额
class CQueue(object):
def __init__(self):
self.queue = []
def appendTail(self, value):
"""
:type value: int
:rtype: None
"""
self.queue.append(value)
def deleteHead(self):
"""
:rtype: int
"""
if len(self.queue)>0:
res = self.queue[0]
self.queue = self.queue[1:]
return res
else:
return -1
# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()
官方做法
2个栈,一个专门管读入,一个专门管删除吐出元素来
stackOut空了,就把stackIn都倒进去
class CQueue(object):
def __init__(self):
self.stackIn = []
self.stackOut = []
def appendTail(self, value):
"""
:type value: int
:rtype: None
"""
self.stackIn.append(value)
def deleteHead(self):
"""
:rtype: int
"""
if not self.stackOut:
if not self.stackIn:
#2个都是空的
return-1
else:
while self.stackIn:
self.stackOut.append(self.stackIn.pop())
return self.stackOut.pop()
# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()
惊奇的是,我的做法比这种快一点。。。
不知道是什么原因额
Day3
困难题
实现正则表达式"*“与”."
简单做法:
充分利用递归
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if not p: return not s # 结束条件
first_match = (len(s) > 0) and p[0] in {s[0], '.'}
# 先处理 `*`
if len(p) >=2 and p[1] == '*':
# 匹配0个 | 多个
return self.isMatch(s, p[2:]) or (first_match and self.isMatch(s[1:], p))
# 处理 `.` ,匹配一个
return first_match and self.isMatch(s[1:], p[1:])
复杂做法:
动态规划
p[1]是"*“就回溯,不是”*"就可以减而治之