LeetCode Weekly contest 190

LeetCode Weekly contest 190_第1张图片
字符串

class Solution {
public:
    int isPrefixOfWord(string sentence, string searchWord) {
        sentence += " ";

        string cur = "";// 分割字符串
        int idx = 1, m = searchWord.size();
        for(auto c : sentence){
            if(c == ' '){
                if(m <= cur.length()){
                    bool flag =true;
                    for(int i = 0; i < m && flag; i ++){
                        if(cur[i] != searchWord[i]) flag = false;
                    }
                    if(flag) return idx;
                }
                cur = "", idx ++;
            }
            else cur += c;
        }
        return -1;
    }
};

LeetCode Weekly contest 190_第2张图片
滑动窗口

class Solution {
public:
    int cal(char c)
    {
        return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
    }

    int maxVowels(string s, int k) {
        int n = s.size();
        int sum = 0; //当前窗口的元音字母数量
        //统计前k个 字母的元音数目
        for(int i = 0; i < k; i ++) sum += cal(s[i]); 
        //滑动窗口
        int res = sum;
        for(int j = k; j < n; j ++){
            // 向后移动一格,减去最前面的一格
            sum += cal(s[j]) - cal(s[j - k]); 
            res = max(res, sum);
        }
        return res;
    }
};

LeetCode Weekly contest 190_第3张图片
树遍历 + 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:
    //伪回文 统计1-9中 至多有一个数字出现的次数是奇数    
    int cnt[10];
    int res = 0;
    void dfs(TreeNode *root)
    {
        if(root == NULL) return;
        ++cnt[root->val];
        if(root->left == NULL && root->right == NULL) //叶子节点,统计数量
        {
            int c = 0;
            for(int i = 1; i < 10; i ++)
                if(cnt[i] & 1) c++;
            if(c <= 1) res ++;
        }else{
            dfs(root->left);
            dfs(root->right);
        }
        --cnt[root->val];
    }

    int pseudoPalindromicPaths (TreeNode* root) {
        memset(cnt, 0, sizeof(cnt));
        dfs(root);
        return res;
    }
};

LeetCode Weekly contest 190_第4张图片
LeetCode Weekly contest 190_第5张图片
动态规划

int dp[555][555];

class Solution {
public:
    int maxDotProduct(vector<int>& a, vector<int>& b) {
        int n = a.size(), m = b.size();
        const int INF = 1e9;
        int res = -INF;
        for(int i = 1; i <= n; i ++)
            for(int j = 1; j <= m; j ++){
                res = max(res, dp[i - 1][j - 1] + a[i - 1] * b[j - 1]);
                dp[i][j] = max({dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1] + a[i - 1] * b[j - 1]});
            }
        return res;
    }
};

你可能感兴趣的:(LeetCode刷题)