1. Two sum
Given an array of integers nums
and an integer target
, return indices of the two numbers
such that they add up to target.
You may assume that each input would have exactly one solution
, and you may not use the same element twice.
You can return the answer in any order.
def twoSum(nums, target):
Dict = {}
length = len(nums)
for i in range(length):
j = target - nums[i]
if j in Dict:
return [Dict[j],i]
Dict[nums[i]] = i
twoSum([2,7,11,15], 9)
[0, 1]
5. Longest Palindromic Substring
Given a string s
, return the longest palindromic substring
in s
- Input: s = “babad”
- Output: “bab”
- Explanation: “aba” is also a valid answer.
def longestPalindrome(s):
left = 0
right = 0
Matrix = [[False]*len(s) for _ in range(len(s))]
MaxLength = 0
for i in range(len(s)-1, -1, -1):
for j in range(i, len(s)):
# print(i, j)
if s[i] == s[j]:
if j-i <= 1 or Matrix[i+1][j-1] is True:
Matrix[i][j] = True
if Matrix[i][j] is True and j-i+1 > MaxLength:
left = i
right = j
MaxLength = j - i + 1
return s[left:right+1]
longestPalindrome('babad')
'aba'