一、力扣20题
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 0:
return True
stack = []
for c in s:
if c == '(' or c == '[' or c == '{':
stack.append(c)
else:
if len(stack) == 0:
return False
else:
temp = stack.pop()
if c == ')':
if temp != '(':
return False
elif c == ']':
if temp != '[':
return False
elif c == '}':
if temp != '{':
return False
return True if len(stack) == 0 else False
解题思路:
这道题采用栈的解法。例如“(())[]”。首先做一个从头到尾的遍历,如果遍历到是左边的符号“(”、“[”、“{”,则放到栈里边。继续往下遍历,如果遇到右边的符号“)”、“]”、“}”,则把栈里边放进去的左边的符号按照后入先出的原则取出,与右边的符号进行匹配,如果能够匹配得上,则返回True。全部遍历完之后,检查栈里还有没有符号,如果栈空就返回True,否则就返回False。
二、力扣21题
class Solution(object):
def mergeTwoLists(self, list1, list2):
"""
:type list1: Optional[ListNode]
:type list2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
res = ListNode()
cur = res
while(list1 !=None and list2 !=None):
if list1.val <= list2.val:
cur.next = list1
list1 = list1.next
else:
cur.next = list2
list2 = list2.next
cur = cur.next
cur.next = list1 or list2
return res.next