365天挑战LeetCode1000题——Day 104 使括号有效的最少添加 翻转二叉树以匹配先序遍历 让字符串成为回文串的最少插入次数

921. 使括号有效的最少添加

在这里插入图片描述

代码实现(模拟)

class Solution {
public:
    int minAddToMakeValid(string s) {
        int count = 0;
        int ans = 0;
        bool usedRight = false;
        for (char c : s) {
            if (c == '(') {
                count++;
            }
            else {
                if (count) {
                    count--;
                }
                else ans++;
            }
            // cout << count << " " << ans << endl;
        }
        return ans + count;
    }
};

971. 翻转二叉树以匹配先序遍历

在这里插入图片描述

代码实现(先序遍历)

/**
 * 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 {
private:
    vector<int> voyage;
    vector<int> ans;
    void match(TreeNode* root, int& pos) {
        // cout << root->val << " " << voyage[pos] << endl;
        if (!root->left && !root->right) return;
        if (root->left) {
            if (root->left->val == voyage[pos]) {
                pos += 1;
                match(root->left, pos);
            }
            else if (root->right && root->right->val == voyage[pos]){
                // cout << "ok" << endl;
                ans.push_back(root->val);
                swap(root->left, root->right);
                pos += 1;
                match(root->left, pos);
            }
            else return;
            if (!root->right || root->right->val != voyage[pos]) return;
            pos += 1;
            match(root->right, pos);
        }
        else {
            if (root->right->val != voyage[pos]) return;
            pos += 1;
            match(root->right, pos);
        }
    }
public:
    vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {
        if (root->val != voyage[0]) return {-1};
        this->voyage = voyage;
        int pos = 1;
        match(root, pos);
        vector<int> d = {-1};
        return pos == voyage.size() ? ans : d;
    }
};

1312. 让字符串成为回文串的最少插入次数

在这里插入图片描述

代码实现(dp)

class Solution {
public:
    int minInsertions(string s) {
        int n = s.size();
        vector<vector<int>> dp(n, vector<int>(n));
        for (int i = n - 2; i >= 0; i--) {
            for (int j = i + 1; j < n; j++) {
                if (s[i] == s[j]) dp[i][j] = dp[i + 1][j - 1];
                else dp[i][j] = min(dp[i][j - 1], dp[i + 1][j]) + 1;
            }
        }
        return dp[0][n - 1];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值