Skip to content

Commit

Permalink
Solution of problems 117, 124, 127, 130, 140, 146, 150, 153, 162, 190…
Browse files Browse the repository at this point in the history
…, 212, 218, 239
  • Loading branch information
Garvit244 committed Jun 5, 2018
1 parent edb07e6 commit f888d81
Show file tree
Hide file tree
Showing 18 changed files with 668 additions and 3 deletions.
4 changes: 4 additions & 0 deletions 1-100q/10.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ def isMatch(self, s, p):
dp = [[False for _ in range(len(p) + 1)] for _ in range(len(s) + 1)]
dp[0][0] = True

for index in range(1, len(dp[0])):
if p[index-1] == '*':
dp[0][index] = dp[0][index - 2]

for index_i in range(1, len(dp)):
for index_j in range(1, len(dp[0])):
if s[index_i - 1] == p[index_j - 1] or p[index_j - 1] == '.':
Expand Down
38 changes: 38 additions & 0 deletions 1-100q/8.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
class Solution:
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
str = str.strip()
number = ""


for x in str:
if x.isalpha() and number == "":
return 0
elif x.isalpha():
break
elif x == ".":
break
elif x == " ":
break
elif (x == "+" or x == "-") and number == "":
number = number + x
elif (x == "+" or x == "-") and number != "":
break
elif (x == "+" or x == "-") and (number[-1] == "+" or number[-1] == "-"):
return 0
elif (x == "+" or x == "-") and ("+" in number or "-" in number):
break
elif x.isdigit():
number = number + x
if number == "" or number == "+" or number == "-":
return 0
else:
if int(number) > ((2**31)-1):
return (2**31)-1
elif int(number) < -(2**31):
return -(2**31)
else:
return int(number)
47 changes: 47 additions & 0 deletions 100-200q/117.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,50 @@ def connect(self, root):
queue.append(front.right)
elif queue:
queue.append(None)


# Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None

class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
if not root:
return None

root.next = None

while root:
temp = root
while temp:
if temp.left:
if temp.right:
temp.left.next = temp.right
else:
temp.left.next = self.getNext(temp)
if temp.right:
temp.right.next = self.getNext(temp)

temp = temp.next
if root.left:
root = root.left
elif root.right:
root = root.right
else:
root = self.getNext(root)

def getNext(self, node):
node = node.next
while node:
if node.left:
return node.left
if node.right:
return node.right
node = node.next
return None
57 changes: 57 additions & 0 deletions 100-200q/124.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
'''
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42
'''

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution(object):
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.result = float('-inf')
self.dfs(root)
return self.result

def dfs(self, root):
if not root:
return 0

l = self.dfs(root.left)
r = self.dfs(root.right)

max_one_end = max(max(l, r)+root.val, root.val)
max_path = max(max_one_end, l+r+root.val)
self.result = max(self.result, max_path)
return max_one_end


4 changes: 3 additions & 1 deletion 100-200q/127.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def ladderLength(self, beginWord, endWord, wordList):
d[s].append(word)
else:
d[s] = [word]

print d
queue, visited = [], set()
queue.append((beginWord, 1))
while queue:
Expand All @@ -60,3 +60,5 @@ def ladderLength(self, beginWord, endWord, wordList):
if neigh not in visited:
queue.append((neigh, steps+1))
return 0

Solution().ladderLength("hit", "cog", ["hot","dot","dog","lot","log","cog"] )
34 changes: 33 additions & 1 deletion 100-200q/130.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,36 @@ def solve(self, board):
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""

if len(board) == 0:
return
for row in range(len(board)):
if board[row][0] == 'O':
self.merge(board, row, 0)
if board[row][len(board[0])-1] == 'O':
self.merge(board, row, len(board[0])-1)

for col in range(len(board[0])):
if board[0][col] == 'O':
self.merge(board, 0, col)

if board[len(board)-1][col] == 'O':
self.merge(board, len(board)-1, col)

for row in range(len(board)):
for col in range(len(board[0])):
if board[row][col] == 'O':
board[row][col] = 'X'
elif board[row][col] == '#':
board[row][col] = 'O'

def merge(self, board, row, col):
if row < 0 or col < 0 or row >= len(board) or col >= len(board[0]):
return
if board[row][col] != 'O':
return

board[row][col] = '#'
self.merge(board, row+1, col)
self.merge(board, row, col-1)
self.merge(board, row, col+1)
self.merge(board, row-1, col)
30 changes: 30 additions & 0 deletions 100-200q/140.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
self.result = []
self.dfs(s, wordDict, '')
return self.result

def dfs(self, s, wordDict, currStr):
if self.check(s, wordDict):
if len(s) == 0:
self.result.append(currStr[1:])
for i in range(1, len(s)+1):
if s[:i] in wordDict:
self.dfs(s[i:], wordDict, currStr + ' ' + s[:i])

def check(self, s, wordDict):
dp = [False for _ in range(len(s)+1)]
dp[0] = True

for i in range(len(s)):
for j in range(i, -1, -1):
if dp[j] and s[j:i+1] in wordDict:
dp[i+1] = True
break

return dp[len(s)]
97 changes: 97 additions & 0 deletions 100-200q/146.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
'''
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
'''

class Node(object):
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
self.prev = None

class LRUCache(object):

def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.mapping = dict()
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.next = self.tail
self.tail.prev = self.head


def get(self, key):
"""
:type key: int
:rtype: int
"""
if key in self.mapping:
node = self.mapping[key]
self.remove(node)
self.add(node)
return node.value
return -1


def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""

if key in self.mapping:
self.remove(self.mapping[key])

node = Node(key, value)
if len(self.mapping) >= self.capacity:
next_head = self.head.next
self.remove(next_head)
del self.mapping[next_head.key]

self.add(node)
self.mapping[key] = node

def add(self, node):
tail = self.tail.prev
tail.next = node
self.tail.prev = node
node.prev = tail
node.next = self.tail

def remove(self, node):
prev_node = node.prev
prev_node.next = node.next
node.next.prev = prev_node




# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
Loading

0 comments on commit f888d81

Please sign in to comment.