(1)20.Valid Parentheses
题目:
分析:
利用stack的思想,首先用python实现的一个stack类,然后对输入的字符串进行遍历,如果是'(','{','[',则将其压栈,否则将当前的字符与栈顶的字符进行比较,如果是匹配的左右符号,则继续循环,否则不匹配或者栈为空,则返回False,循环结束后,判断栈是否为空,如果为空则返回True,否则返回False。
代码:
class Stack():
def __init__(self):
self.items = []
def push(self,value):
self.items.append(value)
def pop(self):
self.items.pop()
def is_empty(self):
return len(self.items) == 0
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if s=="":
return True
i = 0
length = len(s)
# print(length)
stack = Stack()
while i < length:
if s[i] == '(' or s[i] == '[' or s[i] == '{':
stack.push(s[i])
elif s[i] == ')' or s[i] == ']' or s[i] == '}':
if s[i] == ')':
if stack.is_empty() == False and stack.peek() == '(':
stack.pop()
else:
return False
elif s[i] == '}':
if stack.is_empty() == False and stack.peek() == '{':
stack.pop()
else:
return False
else:
if stack.is_empty() == False and stack.peek() == '[':
stack.pop()
else:
return False
else :
return False
i = i + 1
if stack.is_empty() == False:
return False
return True
(2)53.Maximum Subarray
题目:
分析:
遍历数组列表,用两个变量存储总和,一个存储当前连续元素的和的最大值,一个存储从开头到当前元素和的最大值,最后返回final_sum表示连续元素的最大值。
代码:
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums :
current_sum = final_sum = nums[0]
for i in nums[1:]:
current_sum = max(i,current_sum+i)
final_sum = max(final_sum,current_sum)
return final_sum
else:
return 0
53
.
Maximum Subarray