题71(中等):
python代码:
class Solution:
def simplifyPath(self, path: str) -> str:
#首先根据/分割字符串,再使用栈来遍历存储
p_list=path.split('/')
p_stack=[]
for i in p_list:
#如果为空则肯定是//或者///
if i=='':
continue
#如果为..则s_stack要退一个
if i=='..':
if p_stack!=[]:
p_stack.pop()
continue
#如果为.则取当前目录(即为无事发生)
if i=='.':
continue
p_stack.append(i)
return '/'+'/'.join(p_stack)
题72(中等):
python代码:
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
#我感觉要使用动态规划
m=len(word1)
n=len(word2)
dp=[[0]*(n+1) for _ in range(m+1)]
for i in range(m+1):
for j in range(n+1):
if i==0:
dp[i][j]=j
elif j==0:
dp[i][j]=i
for i in range(1,m+1):
for j in range(1,n+1):
if word1[i-1]==word2[j-1]:
dp[i][j]=dp[i-1][j-1]
else:
dp[i][j]=min(dp[i-1][j],dp[i-1][j-1],dp[i][j-1])+1
return dp[-1][-1]
题73(中等):
python代码:
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
#先找0在设置
row=set()
col=set()
m=len(matrix)
if m==0:
return
n=len(matrix[0])
if n==0:
return
for i in range(m):
for j in range(n):
if matrix[i][j]==0:
col.add(j)
row.add(i)
for i in list(row):
for j in range(n):
matrix[i][j]=0
for i in range(m):
for j in list(col):
matrix[i][j]=0
题74(中等):
python代码
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
#和每一行最后一个比,如果大于它就肯定在该行或者不存在,小于就往下看
m=len(matrix)
if m==0:
return False
n=len(matrix[0])
if n==0:
return False
for i in range(m):
if target<matrix[i][n-1]:
return target in matrix[i]
elif target==matrix[i][n-1]:
return True
else:
continue
return False
题75(中等):
分析:
这题我一开始是想双指针,但是中间的1很麻烦就放弃,用了最朴素的统计0,1,2数量方法,但是后面我学到了使用3指针,
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
#学到一个3指针法
p0,p1,p2=0,0,len(nums)-1
while p1<=p2:
if nums[p1]==0:
#如果0在中间,就往边上丢,p0与p1之间一定是1,所以换来p1也加1
nums[p0],nums[p1]=nums[p1],nums[p0]
p1+=1
p0+=1
elif nums[p1]==2:
nums[p1],nums[p2]=nums[p2],nums[p1]
p2-=1
elif nums[p1]==1:
p1+=1