品牌设计的英文百度seo关键词优化方案
记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
目录
- 3/24 2255. 统计是给定字符串前缀的字符串数目
- 3/25 2711. 对角线上不同值的数量差
- 3/26 2829. k-avoiding 数组的最小总和
- 3/27 2712. 使所有字符相等的最小成本
- 3/28 2716. 最小化字符串长度
- 3/29 2360. 图中的最长环
- 3/30 2109. 向字符串添加空格
3/24 2255. 统计是给定字符串前缀的字符串数目
依次判断
def countPrefixes(words, s):""":type words: List[str]:type s: str:rtype: int"""ans=0for w in words:if s.startswith(w):ans+=1return ans
3/25 2711. 对角线上不同值的数量差
模拟每一个位置的数值
def differenceOfDistinctValues(grid):""":type grid: List[List[int]]:rtype: List[List[int]]"""n,m=len(grid),len(grid[0])ans=[[0]*m for _ in range(n)]for i in range(n):for j in range(m):left=set()x,y=i-1,j-1while x>=0 and y>=0:left.add(grid[x][y])x-=1y-=1right=set()x,y=i+1,j+1while x<n and y<m:right.add(grid[x][y])x+=1y+=1ans[i][j]=abs(len(left)-len(right))return ans
3/26 2829. k-avoiding 数组的最小总和
为了总和最小 并且两个数值相加不等于k
小于k的数可以取前一半 k//2
剩余的数 等于k后择取连续的即可 k,k+1,k+2…
def minimumSum(n, k):""":type n: int:type k: int:rtype: int"""num = k//2if num>=n:return (1+n)*n/2else:return (1+num)*num/2+(2*k+n-num-1)*(n-num)/2
3/27 2712. 使所有字符相等的最小成本
对于某个位置x s[x]!=s[x+1]
必须要进行翻转操作 0~x 或者x+1~n 从而使得s[x]=s[x+1]
操作并不会影响其他相邻位置是否相同的状态
所以从头遍历 遇到不相同的进行最有操作min(x,n-x)
def minimumCost(s):""":type s: str:rtype: int"""n=len(s)ans=0for i in range(1,n):if s[i-1]!=s[i]:ans+=min(i,n-i)return ans
3/28 2716. 最小化字符串长度
根据题意 即为将字符去重
def minimizedStringLength(s):""":type s: str:rtype: int"""return len(set(s))
3/29 2360. 图中的最长环
依次遍历 如果出现遍历过的节点说明存在环
def longestCycle(edges):""":type edges: List[int]:rtype: int"""n=len(edges)tag=[0]*ncur = 0ans=-1for i in range(n):if tag[i]>0:continueloc=istart=curwhile loc!=-1:cur+=1if tag[loc]>0:if tag[loc]>start:ans=max(ans,cur-tag[loc])breaktag[loc]=curloc=edges[loc]return ans
3/30 2109. 向字符串添加空格
依次遍历 到位置加入空格
def addSpaces(s, spaces):""":type s: str:type spaces: List[int]:rtype: str"""n = len(s)m = len(spaces)loc = 0ans = []for i in range(n):c = s[i]if loc==m:ans.append(c)else:if i==spaces[loc]:ans.append(" ")loc+=1ans.append(c)return "".join(ans)