算法-数据结构-栈与列表

1. 有效的括号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack=[]
kuo_hao={"(":")","{":"}","[":"]"}
for a in s:
if a in kuo_hao:
stack.append(a)
else:
if not stack:
return False
if stack and kuo_hao[stack.pop()]!=a:
return False
return not stack

2. 两个队列实现一个栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 存使用l ,取也是l只不过是最后一个。
class MyStack(object):

def __init__(self):
"""
Initialize your data structure here.
"""
self.queue_l=[]
self.queue_r=[]


def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: None
"""
self.queue_l.append(x)


def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
while len(self.queue_l)>1:
self.queue_r.append(self.queue_l.pop(0))
value= self.queue_l.pop(0)
while self.queue_r:
self.queue_l.append(self.queue_r.pop(0))
return value


def top(self):
"""
Get the top element.
:rtype: int
"""
while len(self.queue_l)>1:
self.queue_r.append(self.queue_l.pop(0))
value= self.queue_l.pop(0)
if value is not None:
self.queue_r.append(value)
while self.queue_r:
self.queue_l.append(self.queue_r.pop(0))
return value


def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return not self.queue_l

3. 两个栈实现一个队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# 存放在l,取从r中取,再把r中值晴空写回l
class MyQueue(object):

def __init__(self):
"""
Initialize your data structure here.
"""
self.stack_l = []
self.stack_r = []

def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: None
"""
self.stack_l.append(x)

def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
while self.stack_l:
self.stack_r.append(self.stack_l.pop())
value= self.stack_r.pop()
while self.stack_r:
self.stack_l.append(self.stack_r.pop())
return value

def peek(self):
"""
Get the front element.
:rtype: int
"""
while self.stack_l:
self.stack_r.append(self.stack_l.pop())
value= self.stack_r.pop()
self.stack_r.append(value)
while self.stack_r:
self.stack_l.append(self.stack_r.pop())
return value

def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
while self.stack_l:
self.stack_r.append(self.stack_l.pop())
return (not self.stack_r)