①
双指针跑一边即可
class Solution {
public:
int maxPower(string s) {
int res=0;
for(int i=0;i<s.size();)
{
int j=i+1;
while(s[i]==s[j]&&j<s.size()) j++;
res=max(res,j-i);
i=j;
}
return res;
}
};
②
直接遍历一遍即可 最简分数的最大公约数一定是1
class Solution {
public:
int gcd(int a,int b)
{
return b?gcd(b,a%b):a;
}
vector<string> simplifiedFractions(int n) {
vector<string> res;
for(int i=2;i<=n;i++)
for(int j=1;j<i;j++)
{
if(gcd(i,j)==1) res.push_back(to_string(j)+'/'+to_string(i));
}
return res;
}
};
③
dfs遍历树
/**
* 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:
int dfs(TreeNode* root,int maxv)
{
if(!root) return 0;
int res=maxv<=root->val;
maxv=max(maxv,root->val);
res+=dfs(root->left,maxv)+dfs(root->right,maxv);
return res;
}
int goodNodes(TreeNode* root) {
return dfs(root,INT_MIN);//刚开始的max应设为最小值
}
};
④
类似完全背包问题
class Solution {
public:
string largestNumber(vector<int>& cost, int target) {
vector<vector<int>> f(10,vector<int>(target+1));
for(int i=1;i<=target;i++) f[0][i]=-2e9;
for(int i=1;i<=9;i++)
for(int j=0;j<=target;j++)
{
f[i][j]=f[i-1][j];
if(j>=cost[i-1]) f[i][j]=max(f[i][j],f[i][j-cost[i-1]]+1);
}
if(f[9][target]<-1) return "0";
string res;
for(int i=9,j=target;i;i--)
{
while(j>=cost[i-1]&&f[i][j]==f[i][j-cost[i-1]]+1)
{
res+=(to_string(i));
j -= cost[i - 1];
}
}
return res;
}
};