Weekly Contest 311
Problem A
Smallest Even Multiple
思路
水题,判一下奇偶就行
代码
class Solution:
def smallestEvenMultiple(self, n: int) -> int:
if n%2==0:
return n
else:
return 2*n
Problem B
Length of the Longest Alphabetical Continuous Substring
思路
滑动窗口,从左往右扫就行
代码
class Solution:
def longestContinuousSubstring(self, s: str) -> int:
l = 0
r = 1
ans = 1
for i in range(1,len(s)):
t = s[i]
if ord(t)-ord(s[i-1])!=1:
ans = max(ans,r-l)
l = i
r = i+1
else:
r+=1
ans = max(ans,r-l)
return ans
Problem C
Reverse Odd Levels of Binary Tree
思路
BFS,遇到奇数层先存储,到下一层之后再将上面的层反转重新赋值
代码
from queue import Queue
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
q = Queue()
q.put([root,0])
val = []
tree = []
while q.empty() == False:
r,d = q.get()
if d%2==0:
if len(val)!=0:
val = val[::-1]
for i in range(len(val)):
tree[i].val = val[i]
val = []
tree = []
else:
val.append(r.val)
tree.append(r)
if r.left is not None:
q.put([r.left,d+1])
q.put([r.right,d+1])
if len(val)!=0:
val = val[::-1]
for i in range(len(val)):
tree[i].val = val[i]
return root
Problem D
Sum of Prefix Scores of Strings
思路
字典树,抄的板子,所以就只有C++的了
代码
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
char S[maxn];
struct Trie{
int next[26];
int cnt;
void init() {
cnt = 0;
memset(next, -1, sizeof next);
}
}T[maxn];
int le;
void Insert(string s) {
int p = 0;
for (int i = 0; i < s.size(); i++) {
int r = s[i] - 'a';
if(T[p].next[r] == -1) {
T[le].init();
T[p].next[r] = le++;
}
p = T[p].next[r];
T[p].cnt++;
}
}
int query(string s) {
int p = 0;
int ans =0;
for (int i = 0; i < s.size(); i++) {
int r = s[i] - 'a';
if(T[p].next[r] == -1) {
// cout<<0<<endl;
return 0;
}
ans+=T[p].cnt;
p = T[p].next[r];
}
return ans+T[p].cnt;
}
class Solution {
public:
vector<int> sumPrefixScores(vector<string>& words) {
T[0].init();
le = 1;
int len = words.size();
for(int i= 0;i<len;++i){
Insert(words[i]);
}
vector<int> t;
for(int i= 0;i<len;++i){
t.push_back(query(words[i]));
}
return t;
}
};
总结
有进步 能靠板子出4题了
标签:val,Contest,int,311,len,next,ans,self,Weekly From: https://www.cnblogs.com/baihualiaoluan/p/16726787.html