第一题:6180. 最小偶倍数
思路:简单的while循环直到找到符合要求的数即可
class Solution { public: int smallestEvenMultiple(int n) { int k = n; while(k % 2 != 0 || k % n != 0){ k++; } return k; } };
思路:双指针,满足则继续,不满足更新指针,返回最大值即可
class Solution { public: int longestContinuousSubstring(string s) { int res = 1; int i = 0, j = 1, k = 1; while(i < s.size()){ if(s[i] + k == s[j]){ res = max(res,j - i + 1); j++; k++; } else { i++; j = i + 1; k = 1; if(j == s.size()) break; } } return res; } };
第三题:6182. 反转二叉树的奇数层
思路:利用递归一层层向下遍历,如果层数为奇数则将该层的值进行交换即可
/** * 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: void RreverseOddLevels(TreeNode* left, TreeNode* right, int layer){ if(left == nullptr) return;//因为是完美二叉树 管一边就可以 if(layer % 2){ int tmp = left->val; left->val = right->val; right->val = tmp; } RreverseOddLevels(left->left,right->right,layer+1); RreverseOddLevels(left->right,right->left,layer+1); } TreeNode* reverseOddLevels(TreeNode* root) { RreverseOddLevels(root->left,root->right,1); return root; } };
第四题:2416. 字符串的前缀分数和
思路:这题可以去看acwing基础课的第二讲,用到的是trie(字典树),可以高效的存储和读取字符串以及数量,然后在y总给的模板的基础上,根据题意所要求的前缀进行修改即可,难点就是根据题目最坏情况n^2,也就是1e6开辟的数组在leetcode里会爆掉,然后一点点往下减发现4e5就可以了
const int N = 400010;//难点在于数组的大小开辟,最坏可能就是n^2,也就是1e6,数据过大, class Solution { public: int son[N][26],cnt[N],idx; vector<int> sumPrefixScores(vector<string>& words) { int n = words.size(); for(int i = 0; i < n; i++){ int p = 0; for(int j = 0; j < words[i].size(); j++){ int u = words[i][j] - 'a'; if(!son[p][u]) son[p][u] = ++idx; p = son[p][u]; cnt[p]++;//y总的模板的基础上根据题意改动 } } vector<int> res(n,0); for(int i = 0; i < n; i++){ int p = 0; for(int j = 0; j < words[i].size(); j++){ int u = words[i][j] - 'a'; p = son[p][u]; res[i] += cnt[p]; } } return res; } };