Skip to content

Commit fe7acbe

Browse files
committed
update
1 parent a94254a commit fe7acbe

29 files changed

Lines changed: 524 additions & 478 deletions

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22
*.pyc
33
main
44
Python2/
5+
LintCode

LeetCode/Python/006 ZigZag Conversion.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,25 +23,22 @@
2323
class Solution(object):
2424
'''算法思路:
2525
26-
观察,把每一行保存到一个数组里边
26+
观察可知,具有明显的周期性
2727
'''
2828
def convert(self, s, numRows):
29-
if numRows < 1:
30-
return ''
29+
rows = range(numRows) + range(numRows - 2, 0, -1)
3130

32-
if numRows == 1:
33-
return s
31+
r, i, n = [[] for _ in range(numRows)], 0, len(s)
32+
while i < n:
33+
for row in rows:
34+
if i >= n:
35+
break
3436

35-
rows, n = [''] * min(numRows, len(s)), 2 * numRows - 2
37+
r[row].append(s[i])
38+
i += 1
3639

37-
for i, char in enumerate(s):
38-
mod = i % n
39-
if mod > n / 2:
40-
mod = n - mod
40+
return ''.join(map(''.join, r))
4141

42-
rows[mod] += char
43-
44-
return ''.join(rows)
4542

4643

4744
s = Solution()

LeetCode/Python/008 String to Integer (atoi).py

Lines changed: 21 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -26,57 +26,35 @@ class Solution(object):
2626
注意 int 的范围 -2^31 ~ 2^31-1
2727
'''
2828
def myAtoi(self, str):
29-
first, max, min = None, pow(2, 31) - 1, -pow(2, 31)
30-
for i, c in enumerate(str):
31-
if not c.isspace():
32-
first = i
33-
break
29+
MAX_INT, MIN_INT = 2**31 - 1, -2**31
3430

35-
if first is None or (
36-
str[first] not in ['-', '+'] and not str[first].isdigit()):
37-
return 0
31+
str = str.strip()
32+
negative = -1 if (str and str[0] == '-') else 1
3833

39-
negative = False
40-
if str[first] == '-':
41-
negative = True
42-
first += 1
43-
elif str[first] == '+':
44-
first += 1
34+
i = 0
35+
if str and str[0] in ['-', '+']:
36+
i += 1
4537

46-
end = first
47-
while end < len(str):
48-
if not str[end].isdigit():
38+
r = []
39+
while i < len(str):
40+
if str[i].isdigit():
41+
r.append(int(str[i]))
42+
else:
4943
break
50-
end += 1
51-
52-
if end == first:
53-
return 0
54-
55-
end -= 1
56-
57-
while first <= end and str[first] == '0':
58-
first += 1
59-
60-
if first > end:
61-
return 0
62-
63-
sum, i = 0, 1
64-
while end >= first:
65-
plus = (ord(str[end]) - ord('0')) * i
66-
if negative and -min - plus < sum:
67-
return min
44+
i += 1
6845

69-
if not negative and max - plus < sum:
70-
return max
46+
num, base = 0, 1
47+
for i in range(len(r) - 1, -1, -1):
48+
if negative == 1 and MAX_INT - base * r[i] <= num:
49+
return MAX_INT
7150

72-
sum += plus
73-
i *= 10
74-
end -= 1
51+
if negative == -1 and MAX_INT + 1 - base * r[i] <= num:
52+
return MIN_INT
7553

76-
if negative:
77-
sum = -sum
54+
num += base * r[i]
55+
base *= 10
7856

79-
return sum
57+
return num * negative
8058

8159

8260
s = Solution()

LeetCode/Python/012 Integer to Roman.py

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,24 @@
1111

1212

1313
class Solution(object):
14+
'''算法思路:
15+
16+
按单位从大到小,依次过滤
17+
'''
1418
def intToRoman(self, num):
15-
values = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
16-
chars = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX',
17-
'V', 'IV', 'I')
18-
19-
i, r = 0, ''
20-
while i < len(values):
21-
div, num = divmod(num, values[i])
22-
r += chars[i] * div
23-
i += 1
24-
return r
19+
units = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'),
20+
(90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'),
21+
(5, 'V'), (4, 'IV'), (1, 'I')]
22+
23+
r, pointer = [], 0
24+
while num > 0:
25+
while units[pointer][0] > num:
26+
pointer += 1
27+
28+
times, num = divmod(num, units[pointer][0])
29+
r.append(units[pointer][1] * times)
30+
31+
return ''.join(r)
2532

2633

2734
s = Solution()

LeetCode/Python/013 Roman to Integer.py

Lines changed: 14 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -14,40 +14,24 @@ class Solution(object):
1414
'''算法思路:
1515
1616
从维基百科得到罗马数字的表示方式 https://en.wikipedia.org/wiki/Roman_numerals
17+
18+
只有 I, X, C 可以作为前缀
1719
'''
1820
def romanToInt(self, s):
19-
maps = {
20-
'I': 1,
21-
'V': 5,
22-
'X': 10,
23-
'L': 50,
24-
'C': 100,
25-
'D': 500,
26-
'M': 1000
27-
}
28-
29-
combins = {
30-
'IV': 4,
31-
'IX': 9,
32-
'XL': 40,
33-
'XC': 90,
34-
'CD': 400,
35-
'CM': 900
36-
}
37-
38-
prefixs = ['I', 'X', 'C']
39-
40-
i, sum = 0, 0
41-
while i < len(s):
42-
if s[i] in prefixs and i + 1 < len(s) and s[i] + s[i+1] in combins:
43-
sum += combins[s[i] + s[i+1]]
21+
maps = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
22+
combines = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900}
23+
specials = {'I', 'X', 'C'}
24+
25+
r, i, n = 0, 0, len(s)
26+
while i < n:
27+
if s[i] in specials and s[i:i + 2] in combines:
28+
r += combines[s[i:i + 2]]
4429
i += 2
45-
continue
46-
47-
sum += maps[s[i]]
48-
i += 1
30+
else:
31+
r += maps[s[i]]
32+
i += 1
33+
return r
4934

50-
return sum
5135

5236

5337
s = Solution()

LeetCode/Python/014 Longest Common Prefix.py

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,24 +15,20 @@ class Solution(object):
1515
每次前进 1 步,比较每个 str 的相应位的值是否都相等
1616
'''
1717
def longestCommonPrefix(self, strs):
18-
i, prefix = 0, ''
19-
while 1:
18+
prefix, i = [], 0
19+
while strs:
2020
char = None
2121
for s in strs:
22-
if i >= len(s):
23-
return prefix
22+
if i >= len(s) or char is not None and s[i] != char:
23+
return ''.join(prefix)
2424

25-
char = char or s[i]
26-
if char != s[i]:
27-
return prefix
25+
if char is None:
26+
char = s[i]
2827

29-
if not char:
30-
break
31-
32-
prefix += char
3328
i += 1
29+
prefix.append(char)
3430

35-
return prefix
31+
return ''.join(prefix)
3632

3733

3834
s = Solution()

LeetCode/Python/017 Letter Combinations of a Phone Number.py

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,33 @@ class Solution(object):
2323
2424
递归
2525
'''
26-
def letterCombinations(self, digits):
27-
maps = [
28-
'', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
2926

30-
if not digits:
27+
maps = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
28+
29+
def letterCombinations(self, digits, i=0):
30+
if i >= len(digits):
3131
return []
3232

33-
alphas = maps[int(digits[0])]
34-
if len(digits) == 1:
35-
return list(alphas)
33+
return [
34+
prefix + item
35+
for prefix in self.maps[ord(digits[i]) - 48]
36+
for item in self.letterCombinations(digits, i + 1) or ['']
37+
]
38+
3639

37-
left = self.letterCombinations(digits[1:])
38-
return [a + s for a in alphas for s in left] if alphas else left
40+
class Solution(object):
41+
'''算法思路:
42+
43+
动态规划
44+
'''
45+
maps = ['', '', 'abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
46+
47+
def letterCombinations(self, digits):
48+
dp = []
49+
for char in digits:
50+
dp = [prefix + candidates for prefix in dp or ['']
51+
for candidates in self.maps[ord(char) - 48]]
52+
return dp
3953

4054

4155
s = Solution()

LeetCode/Python/020 Valid Parentheses.py

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,20 @@
1313

1414

1515
class Solution(object):
16-
def isValid(self, s):
17-
lefts, rights = ('(', '{', '['), (')', '}', ']')
18-
maps = dict(zip(lefts, rights))
16+
'''算法思路;
1917
20-
stacks = []
18+
因为其是成对出现的,因此用栈
19+
'''
20+
def isValid(self, s):
21+
stack, table = [], {')': '(', ']': '[', '}': '{'}
2122
for char in s:
22-
if char in lefts:
23-
stacks.append(char)
23+
if char in {'(', '[', '{'}:
24+
stack.append(char)
25+
elif not stack or table[char] != stack[-1]:
26+
return False
2427
else:
25-
if not stacks or maps[stacks[-1]] != char:
26-
return False
27-
28-
del stacks[-1]
29-
30-
if stacks:
31-
return False
32-
33-
return True
28+
stack.pop()
29+
return not stack
3430

3531

3632
s = Solution()

LeetCode/Python/036 Valid Sudoku.py

Lines changed: 12 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -20,35 +20,24 @@
2020
class Solution(object):
2121
'''算法思路:
2222
23-
根据数独特性进行判断即可
23+
根据数独特性进行判断即可, 每一行,每一列,每一个九宫格均不能有重复的
2424
'''
2525
def isValidSudoku(self, board):
26-
N = 9
26+
rows, cols = [[set() for _ in range(9)] for _ in range(2)]
27+
grid = [[set() for _ in range(3)] for _ in range(3)]
2728

28-
for i in xrange(N):
29-
record_row, record_col = {}, {}
29+
for i, row in enumerate(board):
30+
for j, num in enumerate(row):
31+
if num == '.':
32+
continue
3033

31-
for j in xrange(N):
32-
s_row, s_col = board[i][j], board[j][i]
33-
34-
record_row[s_row] = record_row.setdefault(s_row, 0) + 1
35-
record_col[s_col] = record_col.setdefault(s_col, 0) + 1
36-
37-
if (s_row != '.' and record_row[s_row] > 1) or (
38-
s_col != '.' and record_col[s_col] > 1):
34+
if (num in rows[i] or num in cols[j] or
35+
num in grid[i // 3][j // 3]):
3936
return False
4037

41-
for i in xrange(0, 7, 3):
42-
for j in xrange(0, 7, 3):
43-
record = {}
44-
45-
for k in xrange(3):
46-
for l in xrange(3):
47-
s = board[i + k][j + l]
48-
record[s] = record.setdefault(s, 0) + 1
49-
if s != '.' and record[s] > 1:
50-
return False
51-
38+
rows[i].add(num)
39+
cols[j].add(num)
40+
grid[i // 3][j // 3].add(num)
5241
return True
5342

5443

0 commit comments

Comments
 (0)