Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 21bb471

Browse files
Merge pull request youngyangyang04#625 from Eyjan-Huang/master
python代码更新,多题提交
2 parents 73c63cc + 02fcd2c commit 21bb471

11 files changed

+243
-168
lines changed

‎problems/0020.有效的括号.md‎

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -162,18 +162,44 @@ class Solution {
162162

163163
Python:
164164
```python3
165+
# 方法一,仅使用栈,更省空间
165166
class Solution:
166167
def isValid(self, s: str) -> bool:
167-
stack = [] # 保存还未匹配的左括号
168-
mapping = {")": "(", "]": "[", "}": "{"}
169-
for i in s:
170-
if i in "([{": # 当前是左括号,则入栈
171-
stack.append(i)
172-
elif stack and stack[-1] == mapping[i]: # 当前是配对的右括号则出栈
168+
stack = []
169+
170+
for item in s:
171+
if item == '(':
172+
stack.append(')')
173+
elif item == '[':
174+
stack.append(']')
175+
elif item == '{':
176+
stack.append('}')
177+
elif not stack or stack[-1] != item:
178+
return False
179+
else:
173180
stack.pop()
174-
else: # 不是匹配的右括号或者没有左括号与之匹配,则返回false
181+
182+
return True if not stack else False
183+
```
184+
185+
```python3
186+
# 方法二,使用字典
187+
class Solution:
188+
def isValid(self, s: str) -> bool:
189+
stack = []
190+
mapping = {
191+
'(': ')',
192+
'[': ']',
193+
'{': '}'
194+
}
195+
for item in s:
196+
if item in mapping.keys():
197+
stack.append(mapping[item])
198+
elif not stack or stack[-1] != item:
175199
return False
176-
return stack == [] # 最后必须正好把左括号匹配完
200+
else:
201+
stack.pop()
202+
return True if not stack else False
177203
```
178204

179205
Go:

‎problems/0024.两两交换链表中的节点.md‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -160,21 +160,29 @@ class Solution {
160160

161161
Python:
162162
```python
163+
# Definition for singly-linked list.
164+
# class ListNode:
165+
# def __init__(self, val=0, next=None):
166+
# self.val = val
167+
# self.next = next
168+
163169
class Solution:
164170
def swapPairs(self, head: ListNode) -> ListNode:
165-
dummy = ListNode(0) #设置一个虚拟头结点
166-
dummy.next = head
167-
cur = dummy
168-
while cur.next and cur.next.next:
169-
tmp = cur.next #记录临时节点
170-
tmp1 = cur.next.next.next #记录临时节点
171-
172-
cur.next = cur.next.next #步骤一
173-
cur.next.next = tmp #步骤二
174-
cur.next.next.next = tmp1 #步骤三
171+
res = ListNode(next=head)
172+
pre = res
173+
174+
# 必须有pre的下一个和下下个才能交换,否则说明已经交换结束了
175+
while pre.next and pre.next.next:
176+
cur = pre.next
177+
post = pre.next.next
175178

176-
cur = cur.next.next #cur移动两位,准备下一轮交换
177-
return dummy.next
179+
# pre,cur,post对应最左,中间的,最右边的节点
180+
cur.next = post.next
181+
post.next = cur
182+
pre.next = post
183+
184+
pre = pre.next.next
185+
return res.next
178186
```
179187

180188
Go:

‎problems/0150.逆波兰表达式求值.md‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -223,17 +223,19 @@ var evalRPN = function(tokens) {
223223
python3
224224

225225
```python
226-
def evalRPN(tokens) -> int:
227-
stack = list()
228-
for i in range(len(tokens)):
229-
if tokens[i] not in ["+", "-", "*", "/"]:
230-
stack.append(tokens[i])
231-
else:
232-
tmp1 = stack.pop()
233-
tmp2 = stack.pop()
234-
res = eval(tmp2+tokens[i]+tmp1)
235-
stack.append(str(int(res)))
236-
return stack[-1]
226+
class Solution:
227+
def evalRPN(self, tokens: List[str]) -> int:
228+
stack = []
229+
for item in tokens:
230+
if item not in {"+", "-", "*", "/"}:
231+
stack.append(item)
232+
else:
233+
first_num, second_num = stack.pop(), stack.pop()
234+
stack.append(
235+
int(eval(f'{second_num}{item}{first_num}')) # 第一个出来的在运算符后面
236+
)
237+
return int(stack.pop()) # 如果一开始只有一个数,那么会是字符串形式的
238+
237239
```
238240

239241

‎problems/0203.移除链表元素.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -245,13 +245,15 @@ Python:
245245
# def __init__(self, val=0, next=None):
246246
# self.val = val
247247
# self.next = next
248+
248249
class Solution:
249250
def removeElements(self, head: ListNode, val: int) -> ListNode:
250-
dummy_head = ListNode(next=head)#添加一个虚拟节点
251+
dummy_head = ListNode(next=head)
251252
cur = dummy_head
252-
while(cur.next!=None):
253-
if(cur.next.val == val):
254-
cur.next = cur.next.next #删除cur.next节点
253+
254+
while cur.next:
255+
if cur.next.val == val:
256+
cur.next = cur.next.next # 删除下一个节点
255257
else:
256258
cur = cur.next
257259
return dummy_head.next

‎problems/0225.用队列实现栈.md‎

Lines changed: 39 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -294,53 +294,66 @@ Python:
294294

295295
```python
296296
from collections import deque
297+
297298
class MyStack:
299+
298300
def __init__(self):
299301
"""
300-
Initialize your data structure here.
302+
Python普通的Queue或SimpleQueue没有类似于peek的功能
303+
也无法用索引访问,在实现top的时候较为困难。
304+
305+
用list可以,但是在使用pop(0)的时候时间复杂度为O(n)
306+
因此这里使用双向队列,我们保证只执行popleft()和append(),因为deque可以用索引访问,可以实现和peek相似的功能
307+
308+
in - 存所有数据
309+
out - 仅在pop的时候会用到
301310
"""
302-
#使用两个队列来实现
303-
self.que1 = deque()
304-
self.que2 = deque()
311+
self.queue_in = deque()
312+
self.queue_out = deque()
305313

306314
def push(self, x: int) -> None:
307315
"""
308-
Push element x onto stack.
316+
直接append即可
309317
"""
310-
self.que1.append(x)
318+
self.queue_in.append(x)
319+
311320

312321
def pop(self) -> int:
313322
"""
314-
Removes the element on top of the stack and returns that element.
323+
1. 首先确认不空
324+
2. 因为队列的特殊性,FIFO,所以我们只有在pop()的时候才会使用queue_out
325+
3. 先把queue_in中的所有元素(除了最后一个),依次出列放进queue_out
326+
4. 交换in和out,此时out里只有一个元素
327+
5. 把out中的pop出来,即是原队列的最后一个
328+
329+
tip:这不能像栈实现队列一样,因为另一个queue也是FIFO,如果执行pop()它不能像
330+
stack一样从另一个pop(),所以干脆in只用来存数据,pop()的时候两个进行交换
315331
"""
316-
size = len(self.que1)
317-
size -= 1#这里先减一是为了保证最后面的元素
318-
while size > 0:
319-
size -= 1
320-
self.que2.append(self.que1.popleft())
321-
332+
if self.empty():
333+
return None
322334

323-
result = self.que1.popleft()
324-
self.que1, self.que2= self.que2, self.que1#将que2和que1交换 que1经过之前的操作应该是空了
325-
#一定注意不能直接使用que1 = que2 这样que2的改变会影响que1 可以用浅拷贝
326-
return result
335+
for i in range(len(self.queue_in) - 1):
336+
self.queue_out.append(self.queue_in.popleft())
337+
338+
self.queue_in, self.queue_out = self.queue_out, self.queue_in # 交换in和out,这也是为啥in只用来存
339+
return self.queue_out.popleft()
327340

328341
def top(self) -> int:
329342
"""
330-
Get the top element.
343+
1. 首先确认不空
344+
2. 我们仅有in会存放数据,所以返回第一个即可
331345
"""
332-
return self.que1[-1]
346+
if self.empty():
347+
return None
348+
349+
return self.queue_in[-1]
350+
333351

334352
def empty(self) -> bool:
335353
"""
336-
Returns whether the stack is empty.
354+
因为只有in存了数据,只要判断in是不是有数即可
337355
"""
338-
#print(self.que1)
339-
if len(self.que1) == 0:
340-
return True
341-
else:
342-
return False
343-
356+
return len(self.queue_in) == 0
344357

345358
```
346359

‎problems/0232.用栈实现队列.md‎

Lines changed: 34 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -281,48 +281,60 @@ class MyQueue {
281281

282282
Python:
283283
```python
284-
# 使用两个栈实现先进先出的队列
285284
class MyQueue:
285+
286286
def __init__(self):
287287
"""
288-
Initialize your data structure here.
288+
in主要负责push,out主要负责pop
289289
"""
290-
self.stack1 = list()
291-
self.stack2 = list()
290+
self.stack_in = []
291+
self.stack_out = []
292+
292293

293294
def push(self, x: int) -> None:
294295
"""
295-
Push element x to the back of queue.
296+
有新元素进来,就往in里面push
296297
"""
297-
#self.stack1用于接受元素
298-
self.stack1.append(x)
298+
self.stack_in.append(x)
299+
299300

300301
def pop(self) -> int:
301302
"""
302-
Removes the element from in front of queue and returns that element.
303+
1. 检查如果out里面元素,则直接pop
304+
2. 如果out没有元素,就把in里面的元素(除了第一个)依次pop后装进out里面
305+
3. 直接把in剩下的元素pop出来,就是queue头部的
303306
"""
304-
# self.stack2用于弹出元素,如果self.stack2为[],则将self.stack1中元素全部弹出给self.stack2
305-
if self.stack2 == []:
306-
while self.stack1:
307-
tmp = self.stack1.pop()
308-
self.stack2.append(tmp)
309-
return self.stack2.pop()
307+
if self.empty:
308+
return None
309+
310+
if self.stack_out:
311+
return self.stack_out.pop()
312+
else:
313+
for i in range(1, len(self.stack_in)):
314+
self.stack_out.append(self.stack_in.pop())
315+
return self.stack_in.pop()
316+
310317

311318
def peek(self) -> int:
312319
"""
313-
Get the front element.
320+
1. 查out有没有元素,有就把最上面的返回
321+
2. 如果out没有元素,就把in最下面的返回
314322
"""
315-
if self.stack2 == []:
316-
while self.stack1:
317-
tmp = self.stack1.pop()
318-
self.stack2.append(tmp)
319-
return self.stack2[-1]
323+
if self.empty:
324+
return None
325+
326+
if self.stack_out:
327+
return self.stack_out[-1]
328+
else:
329+
return self.stack_in[0]
330+
320331

321332
def empty(self) -> bool:
322333
"""
323-
Returns whether the queue is empty.
334+
只要in或者out有元素,说明队列不为空
324335
"""
325-
return self.stack1 == [] and self.stack2 == []
336+
return not (self.stack_in or self.stack_out)
337+
326338
```
327339

328340

‎problems/0344.反转字符串.md‎

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -162,21 +162,14 @@ class Solution:
162162
Do not return anything, modify s in-place instead.
163163
"""
164164
left, right = 0, len(s) - 1
165-
while(left < right):
165+
166+
# 该方法已经不需要判断奇偶数,经测试后时间空间复杂度比用 for i in range(right//2)更低
167+
# 推荐该写法,更加通俗易懂
168+
while left < right:
166169
s[left], s[right] = s[right], s[left]
167170
left += 1
168171
right -= 1
169-
170-
# 下面的写法更加简洁,但是都是同样的算法
171-
# class Solution:
172-
# def reverseString(self, s: List[str]) -> None:
173-
# """
174-
# Do not return anything, modify s in-place instead.
175-
# """
176-
# 不需要判别是偶数个还是奇数个序列,因为奇数个的时候,中间那个不需要交换就可
177-
# for i in range(len(s)//2):
178-
# s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i]
179-
# return s
172+
180173
```
181174

182175
Go:

‎problems/0541.反转字符串II.md‎

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -155,34 +155,27 @@ class Solution {
155155

156156
Python:
157157
```python
158-
159-
class Solution(object):
160-
def reverseStr(self, s, k):
158+
class Solution:
159+
def reverseStr(self, s: str, k: int) -> str:
161160
"""
162-
:type s: str
163-
:type k: int
164-
:rtype: str
161+
1. 使用range(start, end, step)来确定需要调换的初始位置
162+
2. 对于字符串s = 'abc',如果使用s[0:999] ===> 'abc'。字符串末尾如果超过最大长度,则会返回至字符串最后一个值,这个特性可以避免一些边界条件的处理。
163+
3. 用切片整体替换,而不是一个个替换.
165164
"""
166-
from functools import reduce
167-
# turn s into a list
168-
s = list(s)
169-
170-
# another way to simply use a[::-1], but i feel this is easier to understand
171-
def reverse(s):
172-
left, right = 0, len(s) - 1
165+
def reverse_substring(text):
166+
left, right = 0, len(text) - 1
173167
while left < right:
174-
s[left], s[right] = s[right], s[left]
168+
text[left], text[right] = text[right], text[left]
175169
left += 1
176170
right -= 1
177-
return s
171+
return text
178172

179-
# make sure we reverse each 2k elements
180-
for i in range(0, len(s), 2*k):
181-
s[i:(i+k)] = reverse(s[i:(i+k)])
182-
183-
# combine list into str.
184-
return reduce(lambda a, b: a+b, s)
173+
res = list(s)
174+
175+
for cur in range(0, len(s), 2 * k):
176+
res[cur: cur + k] = reverse_substring(res[cur: cur + k])
185177

178+
return ''.join(res)
186179
```
187180

188181

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /