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 1ed6abe

Browse files
Update to 021
Update to 021
1 parent 48ad8d8 commit 1ed6abe

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

‎Python3/020_Valid_Parentheses.py‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#!usr/bin/env python3
2+
# -*- coding:utf-8 -*-
3+
'''
4+
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
5+
6+
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
7+
'''
8+
9+
10+
class Solution(object):
11+
def isValid(self, s):
12+
"""
13+
:type s: str
14+
:rtype: bool
15+
"""
16+
# Valid str must be even
17+
if len(s) % 2 == 1:
18+
return False
19+
stack = []
20+
left = ("(", "[", "{")
21+
right = (")", "]", "}")
22+
zip(left, right)
23+
for c in s:
24+
if c in left:
25+
stack.append(c)
26+
else:
27+
if not stack:
28+
return False
29+
p = stack.pop()
30+
if left.index(p) != right.index(c):
31+
return False
32+
return len(stack) == 0
33+
34+
35+
if __name__ == "__main__":
36+
assert Solution().isValid("({}){}") == True
37+
assert Solution().isValid("({)}") == False
38+
assert Solution().isValid("}}}") == False
39+
assert Solution().isValid("(((") == False
40+
41+
42+
43+
44+
45+
46+
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!usr/bin/env python3
2+
# -*- coding:utf-8 -*-
3+
'''
4+
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
5+
'''
6+
7+
8+
# Definition for singly-linked list.
9+
class ListNode(object):
10+
def __init__(self, x):
11+
self.val = x
12+
self.next = None
13+
14+
15+
class Solution:
16+
def mergeTwoLists(self, l1, l2):
17+
"""
18+
:type l1: ListNode
19+
:type l2: ListNode
20+
:rtype: ListNode
21+
"""
22+
temp = ListNode(-1)
23+
head = temp
24+
while l1 and l2:
25+
if l1.val > l2.val:
26+
temp.next = l2
27+
l2 = l2.next
28+
else:
29+
temp.next = l1
30+
l1 = l1.next
31+
temp = temp.next
32+
if l1:
33+
temp.next = l1
34+
else:
35+
temp.next = l2
36+
return head.next
37+
38+
39+
if __name__ == "__main__":
40+
assert Solution().mergeTwoLists(ListNode(1), ListNode(2)).val == 1
41+
42+

0 commit comments

Comments
(0)

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