6180. 最小偶倍数
最小公倍数的公式。
代码:
class Solution {
public:
int smallestEvenMultiple(int n) {
return n*2/gcd(2,n);
}
};
6181. 最长的字母序连续子字符串的长度
双指针。
class Solution {
public:
int longestContinuousSubstring(string s) {
int n = s.size();
int ans = 0,cur=0;
for (int i = 0; i < n; i++) {
if(i==0||s[i]-s[i-1]!=1){
cur=1;
}else cur++;
ans=max(cur,ans);
}
return ans;
}
};
6182. 反转二叉树的奇数层
思路:先对二叉树进行一个层次遍历,拿到层次遍历的结果。然后在进行一次层次遍历,遇到深度为偶数则反转这一层节点的值,不是交换节点。如果重新构造一棵二叉树会超时。不知道为啥。
层次遍历采用BFS,DFS都行。
可以把之前写过的代码直接拿过来用。力扣102题
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int> >ans;
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> q;
vector<vector<int> >ans;
if(root==nullptr) {
return ans;
}
q.push(root);
while(!q.empty()){
int len=q.size();
ans.push_back(vector<int>());
int n=ans.size();
for(int i=0;i<len;i++){
TreeNode* front=q.front();
q.pop();
ans.back().push_back(front->val);
if(front->left) q.push(front->left);
if(front->right) q.push(front->right);
}
}
return ans;
}
void dfs1(TreeNode* &root,int d){
if(!root){
return;
}
if(d&1) root->val=ans[d].back(),ans[d].pop_back();
dfs1(root->left,d+1);
dfs1(root->right,d+1);
}
TreeNode* reverseOddLevels(TreeNode* root) {
ans=levelOrder(root);
dfs1(root,0);
return root;
}
};
6183. 字符串的前缀分数和
字典树的模板题。
字典树:也可以成为前缀树,或者Trie树。Trie有两种常见的用途,
- 一个是统计前缀字符或者整个字符出现的次数。
- 另一个就是最大的异或对。
直接Acwing里面的模板题拿过来抄一抄。AcWing835
代码:
const int N=1000010;
int son[N][26],cnt[N],idx;
void insert(string &s){
int p=0;
int n=s.size();
for(int i=0;i<n;i++){
int u=s[i]-'a';
if(!son[p][u]) son[p][u]=++idx;
p=son[p][u];
cnt[p]++;
}
}
int find(string &s){
int p=0;
int n=s.size();
int ans=0;
for(int i=0;i<n;i++){
int u=s[i]-'a';
if(!son[p][u]) return 0;
p=son[p][u];
ans+=cnt[p];
}
return ans;
}
class Solution {
public:
vector<int> sumPrefixScores(vector<string>& words) {
idx = 0;
memset(son, 0, sizeof son);
memset(cnt, 0, sizeof cnt);
for(int i=0;i<=100000;i++) cnt[i]=0;
for(auto&s:words){
insert(s);
}
vector<int> ans;
for(auto&s:words){
ans.push_back(find(s));
}
return ans;
}
};
这里有个力扣比较傻逼的地方就是,他每次计算完之后,都应该将数组置空,否则就会答案错误。