周赛
2264. 字符串中最大的 3 位相同数字
class Solution {
public:
string largestGoodInteger(string num) {
string res;
char c='0';
bool f=false;
for(int i=0;i<num.size()-2;i++)
{
if(num[i]==num[i+1]&&num[i]==num[i+2])
{
if(c<num[i])c=num[i];
f=true;
}
}
if(!f)return res;
for(int i=0;i<3;i++)res+=c;
return res;
}
};
2265. 统计值等于子树平均值的节点数
class Solution {
public:
int cnt=0;
int dfs(TreeNode *root)
{
int sum=root->val;
int v=sum;
if(root->left)sum+=dfs(root->left);
if(root->right)sum+=dfs(root->right);
int n=get_num(root);
if(sum/n==v)cnt++;
return sum;
}
int get_num(TreeNode *root)
{
int s=1;
if(root->left)s+=get_num(root->left);
if(root->right)s+=get_num(root->right);
return s;
}
int averageOfSubtree(TreeNode* root) {
dfs(root);
return cnt;
}
};
2266. 统计打字方案数
class Solution {
public:
const int mod=1e9+7;
int countTexts(string pressedKeys) {
long long f1[int(pressedKeys.size())+10];
long long f2[int(pressedKeys.size())+10];
f1[1]=1,f1[2]=2,f1[3]=4,f1[4]=7;
f2[1]=1,f2[2]=2,f2[3]=4,f2[4]=8;
unordered_map<char,int>mp;
for(int i=2;i<=9;i++)
{
if(i==7||i==9)mp[i+'0']=4;
else mp[i+'0']=3;
}
for(int i=4;i<pressedKeys.size()+10;i++)f1[i]=(f1[i-1]+f1[i-2]+f1[i-3])%mod;
for(int i=5;i<pressedKeys.size()+10;i++)f2[i]=(f2[i-1]+f2[i-2]+f2[i-3]+f2[i-4])%mod;
long long res=1;
char c=pressedKeys[0];
int idx=0;
for(int i=0;i<=pressedKeys.size();i++)
{
if(pressedKeys[i]!=c)
{
if(mp[c]==3)res=(res*f1[i-idx])%mod;
else res=(res*f2[i-idx])%mod;
c=pressedKeys[i];
idx=i;
}
}
return res;
}
};
2267. 检查是否有合法括号字符串路径
class Solution {
public:21
bool hasValidPath(vector<vector<char>>& grid) {
bool f[110][110][210];
memset(f,false,sizeof f);
int n=grid.size(),m=grid[0].size();
f[0][1][0]=f[1][0][0]=true;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
for(int k=0;k<n+m;k++)
{
if(grid[i-1][j-1]=='(')
{
if(k>0)f[i][j][k]=f[i-1][j][k-1]||f[i][j-1][k-1];
}
else f[i][j][k]=f[i-1][j][k+1]||f[i][j-1][k+1];
}
}
}
return f[n][m][0];
}
};
每日一题
942. 增减字符串匹配
class Solution {
public:
vector<int> diStringMatch(string s) {
int l=0,r=s.size();
vector<int>v;
for(int i=0;i<s.size();i++)
{
if(s[i]=='I')v.push_back(l++);
else v.push_back(r--);
}
v.push_back(r--);
return v;
}
};
|