Skip to content

Commit 8528a4a

Browse files
committed
LeetCode Solution
1 parent 54aa37b commit 8528a4a

File tree

1,166 files changed

+39407
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

1,166 files changed

+39407
-0
lines changed

001_Two_Sum.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
class Solution(object):
2+
# def twoSum(self, nums, target):
3+
# """
4+
# :type nums: List[int]
5+
# :type target: int
6+
# :rtype: List[int]
7+
# """
8+
# #n^2
9+
# ls = len(nums)
10+
# for i in range(ls):
11+
# for j in range(i + 1, ls):
12+
# if nums[i] + nums[j] == target:
13+
# return [i, j]
14+
15+
# def twoSum(self, nums, target):
16+
# # hash 1
17+
# hash_nums = {}
18+
# for index, num in enumerate(nums):
19+
# try:
20+
# hash_nums[num].append(index)
21+
# except KeyError:
22+
# hash_nums[num] = [index]
23+
# for index, num in enumerate(nums):
24+
# another = target - num
25+
# try:
26+
# candicate = hash_nums[another]
27+
# if another == num:
28+
# if len(candicate) > 1:
29+
# return candicate
30+
# else:
31+
# continue
32+
# else:
33+
# return [index, candicate[0]]
34+
# except KeyError:
35+
# pass
36+
37+
# def twoSum(self, nums, target):
38+
# # hash 2
39+
# hash_nums = {}
40+
# for index, num in enumerate(nums):
41+
# another = target - num
42+
# try:
43+
# hash_nums[another]
44+
# return [hash_nums[another], index]
45+
# except KeyError:
46+
# hash_nums[num] = index
47+
48+
def twoSum(self, nums, target):
49+
# two point
50+
nums_index = [(v, index) for index, v in enumerate(nums)]
51+
nums_index.sort()
52+
begin, end = 0, len(nums) - 1
53+
while begin < end:
54+
curr = nums_index[begin][0] + nums_index[end][0]
55+
if curr == target:
56+
return [nums_index[begin][1], nums_index[end][1]]
57+
elif curr < target:
58+
begin += 1
59+
else:
60+
end -= 1
61+
62+
63+
if __name__ == '__main__':
64+
# begin
65+
s = Solution()
66+
print s.twoSum([3, 2, 4], 6)

002_Add_Two_Numbers.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Definition for singly-linked list.
2+
class ListNode(object):
3+
def __init__(self, x):
4+
self.val = x
5+
self.next = None
6+
7+
8+
class Solution(object):
9+
# def addTwoNumbers(self, l1, l2):
10+
# """
11+
# :type l1: ListNode
12+
# :type l2: ListNode
13+
# :rtype: ListNode
14+
# """
15+
# last = 0
16+
# head = prev = None
17+
# while True:
18+
# if l2 is None and l1 is None and last == 0:
19+
# break
20+
# val = last
21+
# if l2 is not None:
22+
# val += l2.val
23+
# l2 = l2.next
24+
# if l1 is not None:
25+
# val += l1.val
26+
# l1 = l1.next
27+
# if val >= 10:
28+
# val = val % 10
29+
# last = 1
30+
# else:
31+
# last = 0
32+
# current = ListNode(val)
33+
# if prev is None:
34+
# head = current
35+
# else:
36+
# prev.next = current
37+
# prev = current
38+
# return head
39+
40+
def addTwoNumbers(self, l1, l2):
41+
carry = 0
42+
# dummy head
43+
head = curr = ListNode(0)
44+
while l1 or l2:
45+
val = carry
46+
if l1:
47+
val += l1.val
48+
l1 = l1.next
49+
if l2:
50+
val += l2.val
51+
l2 = l2.next
52+
curr.next = ListNode(val % 10)
53+
curr = curr.next
54+
carry = val / 10
55+
if carry > 0:
56+
curr.next = ListNode(carry)
57+
return head.next
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
class Solution(object):
2+
# def lengthOfLongestSubstring(self, s):
3+
# """
4+
# :type s: str
5+
# :rtype: int
6+
# """
7+
# sls = len(set(s))
8+
# ls = len(s)
9+
# if ls >= 1:
10+
# max_l = 1
11+
# else:
12+
# return 0
13+
# for i in range(ls):
14+
# for j in range(i + max_l + 1, i + sls + 1):
15+
# curr = s[i:j]
16+
# c_ls = len(curr)
17+
# if len(set(curr)) != c_ls:
18+
# break
19+
# else:
20+
# if c_ls > max_l:
21+
# max_l = c_ls
22+
# if max_l == sls:
23+
# return sls
24+
# return max_l
25+
26+
# def lengthOfLongestSubstring(self, s):
27+
# sls = len(set(s))
28+
# ls = len(s)
29+
# if ls >= 1:
30+
# max_l = 1
31+
# else:
32+
# return 0
33+
# for i in range(ls):
34+
# for j in reversed(range(i + max_l + 1, i + sls + 1)):
35+
# curr = s[i:j]
36+
# c_ls = len(curr)
37+
# if len(set(curr)) == c_ls:
38+
# if c_ls > max_l:
39+
# max_l = c_ls
40+
# if max_l == sls:
41+
# return sls
42+
# break
43+
# return max_l
44+
45+
# def lengthOfLongestSubstring(self, s):
46+
# exist = [False] * 256
47+
# ls = len(s)
48+
# max_len = i = 0
49+
# for j in range(ls):
50+
# while(exist[ord(s[j])]):
51+
# exist[ord(s[i])] = False
52+
# i += 1
53+
# exist[ord(s[j)] = True
54+
# max_len = max(max_len, j - i + 1)
55+
# return max_len
56+
57+
def lengthOfLongestSubstring(self, s):
58+
# https://leetcode.com/articles/longest-substring-without-repeating-characters/
59+
charMap = {}
60+
for i in range(256):
61+
charMap[i] = -1
62+
ls = len(s)
63+
i = max_len = 0
64+
for j in range(ls):
65+
# Note that when charMap[ord(s[j])] >= i, it means that there are
66+
# duplicate character in current i,j. So we need to update i.
67+
if charMap[ord(s[j])] >= i:
68+
i = charMap[ord(s[j])] + 1
69+
charMap[ord(s[j])] = j
70+
max_len = max(max_len, j - i + 1)
71+
return max_len

004_Median_of_Two_Sorted_Arrays.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class Solution(object):
2+
# def findMedianSortedArrays(self, nums1, nums2):
3+
# """
4+
# :type nums1: List[int]
5+
# :type nums2: List[int]
6+
# :rtype: float
7+
# """
8+
# p1 = p2 = 0
9+
# ls1 = len(nums1)
10+
# ls2 = len(nums2)
11+
# all_nums = []
12+
# median = 0.0
13+
# while p1 < ls1 and p2 < ls2:
14+
# if nums1[p1] < nums2[p2]:
15+
# all_nums.append(nums1[p1])
16+
# p1 += 1
17+
# else:
18+
# all_nums.append(nums2[p2])
19+
# p2 += 1
20+
# if p1 < ls1:
21+
# while p1 < ls1:
22+
# all_nums.append(nums1[p1])
23+
# p1 += 1
24+
# if p2 < ls2:
25+
# while p2 < ls2:
26+
# all_nums.append(nums2[p2])
27+
# p2 += 1
28+
# # print all_nums
29+
# if (ls1 + ls2) % 2 == 1:
30+
# median = all_nums[(ls1 + ls2) / 2]
31+
# else:
32+
# median = 1.0 * (all_nums[(ls1 + ls2) / 2] + all_nums[(ls1 + ls2) / 2 - 1]) / 2
33+
# return median
34+
35+
def findMedianSortedArrays(self, nums1, nums2):
36+
# https://discuss.leetcode.com/topic/4996/share-my-o-log-min-m-n-solution-with-explanation
37+
# https://discuss.leetcode.com/topic/16797/very-concise-o-log-min-m-n-iterative-solution-with-detailed-explanation
38+
ls1, ls2 = len(nums1), len(nums2)
39+
if ls1 < ls2:
40+
return self.findMedianSortedArrays(nums2, nums1)
41+
l, r = 0, ls2 * 2
42+
while l <= r:
43+
mid2 = (l + r) >> 1
44+
mid1 = ls1 + ls2 - mid2
45+
L1 = -sys.maxint - 1 if mid1 == 0 else nums1[(mid1 - 1) >> 1]
46+
L2 = -sys.maxint - 1 if mid2 == 0 else nums2[(mid2 - 1) >> 1]
47+
R1 = sys.maxint if mid1 == 2 * ls1 else nums1[mid1 >> 1]
48+
R2 = sys.maxint if mid2 == 2 * ls2 else nums2[mid2 >> 1]
49+
if L1 > R2:
50+
l = mid2 + 1
51+
elif L2 > R1:
52+
r = mid2 - 1
53+
else:
54+
return (max(L1, L2) + min(R1, R2)) / 2.0
55+
56+
57+
if __name__ == '__main__':
58+
# begin
59+
s = Solution()
60+
print s.findMedianSortedArrays([1, 1], [1, 2])

005_Longest_Palindromic_Substring.py

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
class Solution(object):
2+
def longestPalindrome(self, s):
3+
"""
4+
:type s: str
5+
:rtype: str
6+
"""
7+
# my solution
8+
# expand string according to Manacher algorithm
9+
# but extend radius step by step
10+
ls = len(s)
11+
if ls <= 1 or len(set(s)) == 1:
12+
return s
13+
# create a new list like this: "abc"->"a#b#c"
14+
temp_s = '#'.join('{}'.format(s))
15+
# print temp_s
16+
tls = len(temp_s)
17+
seed = range(1, tls - 1)
18+
# this table stores the max length palindrome
19+
len_table = [0] * tls
20+
for step in range(1, tls / 2 + 1):
21+
final = []
22+
for pos in seed:
23+
if pos - step < 0 or pos + step >= tls:
24+
continue
25+
if temp_s[pos - step] != temp_s[pos + step]:
26+
continue
27+
final.append(pos)
28+
if temp_s[pos - step] == '#':
29+
continue
30+
len_table[pos] = step
31+
seed = final
32+
max_pos, max_step = 0, 0
33+
for i, s in enumerate(len_table):
34+
if s >= max_step:
35+
max_step = s
36+
max_pos = i
37+
return temp_s[max_pos - max_step:max_pos + max_step + 1].translate(None, '#')
38+
39+
# def longestPalindrome(self, s):
40+
# # example in leetcode book
41+
# max_left, max_right = 0, 0
42+
# ls = len(s)
43+
# for i in range(ls):
44+
# len1 = self.expandAroundCenter(s, i, i)
45+
# len2 = self.expandAroundCenter(s, i, i + 1)
46+
# max_len = max(len1, len2)
47+
# if (max_len > max_right - max_left):
48+
# max_left = i - (max_len - 1) / 2
49+
# max_right = i + max_len / 2
50+
# return s[max_left:max_right + 1]
51+
#
52+
# def expandAroundCenter(self, s, left, right):
53+
# ls = len(s)
54+
# while (left >= 0 and right < ls and s[left] == s[right]):
55+
# left -= 1
56+
# right += 1
57+
# return right - left - 1
58+
59+
# def longestPalindrome(self, s):
60+
# #Manacher algorithm
61+
# #http://en.wikipedia.org/wiki/Longest_palindromic_substring
62+
# # Transform S into T.
63+
# # For example, S = "abba", T = "^#a#b#b#a#$".
64+
# # ^ and $ signs are sentinels appended to each end to avoid bounds checking
65+
# T = '#'.join('^{}$'.format(s))
66+
# n = len(T)
67+
# P = [0] * n
68+
# C = R = 0
69+
# for i in range (1, n-1):
70+
# P[i] = (R > i) and min(R - i, P[2*C - i]) # equals to i' = C - (i-C)
71+
# # Attempt to expand palindrome centered at i
72+
# while T[i + 1 + P[i]] == T[i - 1 - P[i]]:
73+
# P[i] += 1
74+
#
75+
# # If palindrome centered at i expand past R,
76+
# # adjust center based on expanded palindrome.
77+
# if i + P[i] > R:
78+
# C, R = i, i + P[i]
79+
#
80+
# # Find the maximum element in P.
81+
# maxLen, centerIndex = max((n, i) for i, n in enumerate(P))
82+
# return s[(centerIndex - maxLen)//2: (centerIndex + maxLen)//2]
83+
84+
85+
if __name__ == '__main__':
86+
# begin
87+
s = Solution()
88+
print s.longestPalindrome("abcbe")

0 commit comments

Comments
 (0)