一、检查单词是否为句中其他单词的前缀
https://leetcode-cn.com/contest/weekly-contest-190/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/
1、题目描述:
2、题解:
class Solution:
def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
res = sentence.strip().split()
# print(res)
i,j = 0,0
for i in range(len(res)):
if res[i][0] == searchWord[0]:
if len(res[i]) < len(searchWord):
continue
j = 0
while j < len(searchWord) and res[i][j] == searchWord[j]:
j += 1
if j == len(searchWord):
return i + 1
# print(res[2][0])
return -1
二、定长子串中元音的最大数目
https://leetcode-cn.com/contest/weekly-contest-190/problems/maximum-number-of-vowels-in-a-substring-of-given-length/
1、题目描述:
2、题解:
一开始是下面代码,但是超时,
class Solution:
def maxVowels(self, s: str, k: int) -> int:
res = 0
temp = {'a','e','i','o','u'}
left = 0
right = 0
while right < len(s):
right = left
t = 0
while right < len(s) and right-left < k:
if s[right] in temp:
t += 1
right += 1
res = max(res,t)
left += 1
return res
加速:
class Solution:
def maxVowels(self, s: str, k: int) -> int:
res = 0
temp = {'a','e','i','o','u'}
if len(s) <= k:
for i in range(len(s)):
if s[i] in temp:
res += 1
return res
tlist = 0
for i in range(k):
if s[i] in temp:
tlist += 1
res = max(res,tlist)
right = k
while right < len(s):
if s[right - k] in temp and s[right] not in temp:
tlist -= 1
if s[right - k] not in temp and s[right] in temp:
tlist += 1
res = max(res,tlist)
right += 1
return res
三、二叉树中的伪回文路径
1、题目描述:
2、题解:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def pseudoPalindromicPaths (self, root):
s = set()
def dfs(root):
if not root: return 0
if root.val in s:
s.discard(root.val)
else:
s.add(root.val)
res = dfs(root.left) + dfs(root.right)
if not root.left and not root.right:
res += len(s) <= 1
if root.val in s:
s.discard(root.val)
else:
s.add(root.val)
return res
return dfs(root)
四、两个子序列的最大点积
https://leetcode-cn.com/contest/weekly-contest-190/problems/max-dot-product-of-two-subsequences/
1、题目描述:
2、题解:
class Solution(object):
def maxDotProduct(self, A, B):
if all(a < 0 for a in A) and (b > 0 for b in B): return max(A) * min(B)
if all(a > 0 for a in A) and (b < 0 for b in B): return min(A) * max(B)
n,m = len(A), len(B)
dp = [[0] * (m + 1) for i in range(n + 1)]
for i in range(1, n+1):
for j in range(1, m+1):
dp[i][j] = max(dp[i-1][j], dp[i][j-1],dp[i-1][j-1] + A[i-1]*B[j-1])
return dp[n][m]