Merge pull request #3 from TheAlgorithms/master

merge from main.
This commit is contained in:
Anurag Kumar
2017-10-26 12:13:04 +05:30
committed by GitHub
29 changed files with 1173 additions and 124 deletions

View File

@@ -18,28 +18,20 @@ returns true if S is nested and false otherwise.
def is_balanced(S):
stack = []
open_brackets = set({'(', '[', '{'})
closed_brackets = set({')', ']', '}'})
open_to_closed = dict({'{':'}', '[':']', '(':')'})
for i in range(len(S)):
if S[i] == '(' or S[i] == '{' or S[i] == '[':
if S[i] in open_brackets:
stack.append(S[i])
else:
if len(stack) > 0:
pair = stack.pop() + S[i]
if pair != '[]' and pair != '()' and pair != '{}':
return False
else:
elif S[i] in closed_brackets:
if len(stack) == 0 or (len(stack) > 0 and open_to_closed[stack.pop()] != S[i]):
return False
if len(stack) == 0:
return True
return False
return len(stack) == 0
def main():
@@ -48,7 +40,7 @@ def main():
if is_balanced(S):
print(S, "is balanced")
else:
print(S, "is not balanced")

28
other/two-sum.py Normal file
View File

@@ -0,0 +1,28 @@
"""
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
"""
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
chk_map = {}
for index, val in enumerate(nums):
compl = target - val
if compl in chk_map:
indices = [chk_map[compl], index]
print(indices)
return [indices]
else:
chk_map[val] = index
return False