20 Valid Parentheses
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack, lookup = [], {"(": ")", "{": "}", "[": "]"}
for parenthese in s:
if parenthese in lookup:
stack.append(parenthese)
elif len(stack) == 0 or lookup[stack.pop()] != parenthese:
return False
return len(stack) == 0
42. Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
area=0
maxl,maxr=[],[]
tmp=0
for i in range(len(height)):
if height[i]>tmp: tmp=height[i]
maxl.append(tmp)
tmp=0
for i in range(len(height)-1,-1,-1):
if height[i]>tmp: tmp=height[i]
maxr.append(tmp)
area=0
for i in range(1,len(height)-1):
minh=min(maxl[i],maxr[len(height)-i-1])-height[i]
area+=minh if minh>0 else 0
return area
71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
Corner Cases:
Did you consider the case where path = “/../”?
In this case, you should return “/”.
Another corner case is the path might contain multiple slashes ‘/’ together, such as “/home//foo/”.
In this case, you should ignore redundant slashes and return “/home/foo”.
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
stack, tokens = [], path.split("/")
for token in tokens:
if token == ".." and stack:
stack.pop()
elif token != ".." and token != "." and token:
stack.append(token)
return "/" + "/".join(stack)