LeetCode周赛190题解-1455-1456-1457-1458
class Solution {
public:
void SplitString(const std::string& s, std::vector<std::string>& v, const std::string& c){
std::string::size_type pos1, pos2;
pos2 = s.find(c);
pos1 = 0;
while(std::string::npos != pos2)
{
v.push_back(s.substr(pos1, pos2-pos1));
pos1 = pos2 + c.size();
pos2 = s.find(c, pos1);
}
if(pos1 != s.length())
v.push_back(s.substr(pos1));
}
int isPrefixOfWord(string sentence, string searchWord) {
vector<string> t;
int pos = 0;
int len = searchWord.length();
SplitString(sentence, t, " ");
for (int i = 0; i < t.size(); i++) {
if (t[i].substr(0, len) == searchWord) {
return i + 1;
}
}
return -1;
}
};
class Solution {
public:
bool check(char a, string s) {
for (int j = 0; j < 5; j++)
if (a == s[j]) return true;
return false;
}
int maxVowels(string s, int k) {
string a = "aeiou";
int max = 0;
vector<int> n(s.length(), 0);
for (int i = 0; i < s.length(); i++) {
if (check(s[i], a)) {
n[i] = 1;
}
}
for (int i = 0; i < k; i++) {
if (n[i] == 1) max++;
}
int cnt = max;
for (int i = k ; i < s.length(); i++) {
if (check(s[i], a)) { //是元音
if (n[i - k] == 1) continue; //右移以后左边元音被移除
else {
cnt++; //左边不是元音
}
} else { //不是元音
if (n[i - k] == 1) cnt--; //左边元音被移出
}
max = max < cnt ? cnt : max;
}
return max;
}
};
/**
* 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 check(int *cnt) { //检查得到的结点的是否只有一个奇数
int odd = 0;
for(int i = 0; i <= 9; i++) {
if(cnt[i]&1) { // &1判断是否为奇数
odd++;
}
}
if(odd <= 1) { //只有一个奇数或者没有奇数如:22
return 1;
}
return 0;
}
int dfs(TreeNode *root, int *cnt) {
if(root == nullptr) { // 递归出口
return 0;
}
cnt[root->val] ++;
if(root->left == nullptr && root->right == nullptr) { //判断是否到达叶节点 然后调用check
int anw = check(cnt);
cnt[root->val]--; //统计完减去
return anw;
}
int anw = 0;
if(root->left != nullptr) {
anw += dfs(root->left, cnt);
}
if(root->right != nullptr) {
anw += dfs(root->right, cnt);
}
cnt[root->val] --; //统计完减去
return anw;
}
int pseudoPalindromicPaths (TreeNode* root) {
int cnt[10] = {0};
return dfs(root, cnt);
}
};
class Solution {
public:
int maxDotProduct(vector<int>& nums1, vector<int>& nums2) {
int sz1=nums1.size(),sz2=nums2.size();
vector<vector<int>> dp(sz1+1,vector<int>(sz2+1,-1e8));
for(int i=1;i<=sz1;i++){
for(int j=1;j<=sz2;j++){
//1.1
dp[i][j]=nums1[i-1]*nums2[j-1];
//1.2
dp[i][j]=max(dp[i][j],nums1[i-1]*nums2[j-1]+dp[i-1][j-1]);
//2
dp[i][j]=max(dp[i][j],dp[i][j-1]);
//3
dp[i][j]=max(dp[i][j],dp[i-1][j]);
//4
dp[i][j]=max(dp[i][j],dp[i-1][j-1]);
}
}
return dp[sz1][sz2];
}
};