10-正则表达式匹配(python)
#动态规划
class Solution(object):
def isMatch(self, s, p):
# 边界条件,考虑 s 或 p 分别为空的情况
if not p: return not s
if not s and len(p) == 1: return False
m, n = len(s) + 1, len(p) + 1
dp = [[False for _ in range(n)] for _ in range(m)]
# 初始状态
dp[0][0] = True
dp[0][1] = False
for c in range(2, n):
j = c - 1
if p[j] == '*':
dp[0][c] = dp[0][c - 2]
for r in range(1,m):
i = r - 1
for c in range(1, n):
j = c - 1
if s[i] == p[j] or p[j] == '.':
dp[r][c] = dp[r - 1][c - 1]
elif p[j] == '*': # ‘*’前面的字符匹配s[i] 或者为'.'
if p[j - 1] == s[i] or p[j - 1] == '.':
dp[r][c] = dp[r - 1][c] or dp[r][c - 2]
else: # ‘*’匹配了0次前面的字符
dp[r][c] = dp[r][c - 2]
else:
dp[r][c] = False
return dp[m - 1][n - 1]
13-罗马数字转整数(python)
#先判断是否小于后面
class Solution(object):
def romanToInt(self, s):
Roman2Int = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
Int = 0
for index in range(len(s) - 1):
if Roman2Int[s[index]] < Roman2Int[s[index + 1]]:
Int -= Roman2Int[s[index]]
else:
Int += Roman2Int[s[index]]
return Int + Roman2Int[s[-1]]
28-实现strStr()(python)
#先比较第一个字符
class Solution(object):
def strStr(self,haystack,needle):
n=len(haystack)
l=len(needle)
i=0
while i<(n-l):
if haystack[i]==needle[0]:
if haystack[i:i+l]==needle:
return i
else:
i+=1
i+=1
return -1
29-二进制除法(python)
class Solution(object):
def divide(self, dividend, divisor):
res = 0
if dividend == 0:
return res
# 初始化
i = 0
res = 0
p = abs(dividend)
q = abs(divisor)
# 移位对齐被除数的最左端
while q << i <= p:
i = i + 1
# 利用二进制进行除法运算
for j in reversed(range(i)):
if q << j <= p:
p = p - (q << j)
res = res + (1 << j)
# 内存限制
if (dividend > 0) != (divisor > 0) or res < -1 << 31:
res = -res
return min(res, (1 << 31) - 1)
36-有效的数独(python)
#key-value
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
# init data
rows = [{} for i in range(9)]
columns = [{} for i in range(9)]
boxes = [{} for i in range(9)]
# validate a board
for i in range(9):
for j in range(9):
num = board[i][j]
if num != '.':
num = int(num)
box_index = (i // 3 ) * 3 + j // 3
# keep the current cell value
rows[i][num] = rows[i].get(num, 0) + 1
columns[j][num] = columns[j].get(num, 0) + 1
boxes[box_index][num] = boxes[box_index].get(num, 0) + 1
# check if this value has been already seen before
if rows[i][num] > 1 or columns[j][num] > 1 or boxes[box_index][num] > 1:
return False
return True
38-外观数列(python)
#递归
class Solution(object):
def countAndSay(self, n):
if n <= 1:
return '1'
pre = self.countAndSay(n - 1)
res = ''
count = 1
for idx in range(len(pre)):
if idx == 0 :
count = 1
elif pre[idx] != pre[idx -1]:
tmp = str(count) + pre[idx-1]
res += tmp
count = 1
elif pre[idx] == pre[idx-1]:
count +=1
if idx == len(pre) - 1:
tmp = str(count) + pre[idx]
res += tmp
return res
41-缺失的第一个正数(python)
class Solution(object):
def firstMissingPositive(self,nums):
if not nums:return 1
n=len(nums)
for i in range(len(nums)):
while nums[i]>0 and nums[i]!=nums[nums[i]-1]:
nums[i],nums[nums[i]-1]=nums[nums[i]-1],nums[i]
for i in range(len((nums)):
if nums[i]!=i+1:
return i+1
return n+1
44-通配符匹配(? *)(python)
class Solution(object):
def isMatch(self, s, p):
n1=len(s)
n2=len(p)
dp=[[False for i in range(n2+1)] for j in range(n1+1)]#dp[i][j]对应s[:i]和p[:j]是否匹配
dp[0][0]=True
for i in range(1,n2+1):
if dp[0][i-1]==True and p[i-1]=="*":
dp[0][i]=True
for i in range(1,n1+1):
for j in range(1,n2+1):
if dp[i-1][j-1]:
dp[i][j]=(s[i-1]==p[j-1] or p[j-1]=="?" or p[j-1]=="*")
else:
dp[i][j]=(p[j-1]=="*" and (dp[i-1][j] or dp[i][j-1]))
return dp[n1][n2]
50-实现pow(x,n)(python)
class Solution(object):
def mypow(self,x,n):
if n<0:return 1/self.helper(x,-n)
def helper(self,x,n):
if n==0:return 1
if n%2==0:return self.helper(x*x,n//2)
return self.helper(x*x,(n-1)//2)
66-加一(python)
#判断进位
class Solution(object):
def plusone(self,digits):
carry=1
for i in range(len(digits)-1,-1,-1):
if digits[i]==9:
if carry==1:
digits[i]=0
carry=1
else:
digits[i]+=carry
carry=0
if carry==1:
digits=[1]+digits
return digits
69-x的平方根(python)
#二分查找
class Solution(object):
def mysqrt(self,x):
if x<2:return x
left=2
right=x//2
while left<right:
pivot=(left+right)//2
nums=pivot*pivot
if nums>x:right=pivot-1
elif nums<x:left=pivot+1
else:return pivot
return right
73-矩阵置零(python)
#统计置零的行与列
class Solution(object):
def setZeroes(self,matrix):
row=len(matrix)
col=len(matrix[0])
row_zero=set()
col_zero=set()
for i in range(row):
for j in range(col):
if matrix[i][j]==0:
row_zero.add(i)
col_zero.add(j)
for i in range(row):
for j in range(col):
if i in row_zero or j in col_zero:
matrix[i][j]=0
return matrix
91-解码方法(python)
#动态规划 dp[i]=dp[i-1]+dp[i-2]
class Solution(object):
def numDecoding(self,s):
size=len(s)
if size==0:return 0
dp=[0]*(size+1)
dp[0]=1
for i in range(1,size+1):
m=int(s[i-1])
if m>=1 and m<=9:
dp[i]+=dp[i-1]
if i>=2:
m=int(s[i-2])*10+int(s[i-1])
if m>=10 and m<=26:
dp[i]+=dp[i-2]
return dp[-1]
103-二叉树的锯齿形遍历(python)
#用queue保存
class Solution(object):
def zigzagLevelOrder(self, root):
if not root:return []
res=[]
j=1
queue=[root]
while queue:
temp=[]
j+=1
for i in range(len(queue)):
node=queue.pop(0)
temp.append(node.val)
if node.left:queue.append(node.left)
if node.right:queue.append(node.right)
if j%2:temp.reverse()
res.append(temp)
return res
108-将有序数组转为二叉搜索树(python)
class Solution(object):
def sortedArrayToBST(self,nums):
if not nums:
return None
mid=len(nums)//2
node=TreeNode(nums[mid])
left=nums[:mid]
right=nums[mid+1:]
node.left=self.sortedArrayToBST(left)
node.right=self.sortedArrayToBST(right)
return node
116-填充每个节点的下一个右侧节点指针(python)
#递归
class Solution(object):
def connect(self,root):
if not root:return
if root.left:
root.left.next=root.right
if root.next:
root.right.next=root.next.left
self.connect(root.left)
self.connect(root.right)
118-杨辉三角(python)
#动态规划
class Solution(object):
def generate(self,numRows):
dp=[[0]*n for n in range(1,numRows)]
for i in range(numRows):
dp[i][0]=dp[i][-1]=1
for i in range(numRows):
for j in range(i+1):
if dp[i][j]==0:
dp[i][j]=dp[i-1][j]+dp[i-1][j-1]
return dp
125-验证回文串(python)
#双指针
class Solution(object):
def isPalindrome(self,s):
left=0
right=len(s)-1
while left<right:
if s[left]!=s[right]:
return False
left+=1
right-=1
return True
127-单词接龙(python)
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
# 首先给wordList列表中单词去重
word_set = set(wordList)
# 定义当前层的单词集合为beginWord
cur_word = [beginWord]
# 定义下一层的单词集合
next_word = []
# 定义从 beginWord 到 endWord 的最短转换序列的长度
depth = 1
while cur_word:
for word in cur_word:
# 如果endWord出现在当前层的cur_word单词集合中,则立即返回该深度
if word == endWord:
return depth
for index in range(len(word)):
for indice in "abcdefghijklmnopqrstuvwxyz":
new_word = word[:index]+indice+word[index+1:]
if new_word in word_set:
word_set.remove(new_word)
next_word.append(new_word)
# 如果endWord未出现在当前层的cur_word单词集合中,则深度+1
depth += 1
cur_word = next_word
next_word = []
return 0