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


    给你一个字符串 s ,每一次操作你都可以在字符串的任意位置插入任意字符。

    请你返回让 s 成为回文串的 最少操作次数 。

    「回文串」是正读和反读都相同的字符串。

    示例 1:

    输入:s = "zzazz"
    输出:0
    解释:字符串 "zzazz" 已经是回文串了,所以不需要做任何插入操作。
    

    示例 2:

    输入:s = "mbadm"
    输出:2
    解释:字符串可变为 "mbdadbm" 或者 "mdbabdm" 。
    

    示例 3:

    输入:s = "leetcode"
    输出:5
    解释:插入 5 个字符后字符串变为 "leetcodocteel" 

    int minInsertions(string s)
    {
        int size = s.length();
        if (size <=1)
        {
            return 0;
        }
        if (size == 2)
        {
            if (s[0] == s[1])
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }
        int ret = INT_MAX;
        vector curDP(size, 0);
        vector preDP(size, 0);
        vector tmpDP(size, 0);
        //init
        int index = size - 1;
        if (s[0] == s[index])
        {
            preDP[size - 1] = 0;
        }
        else
        {
            preDP[size - 1] = 2;
        }
        index = size - 2;
        while (index > 0)
        {
            int a = size - index;
            int b = preDP[index + 1];
            if (s[0] == s[index])
            {
                preDP[index] = a-1;
            }
            else
            {
                preDP[index] = min(a, b) +1;
            }
            index--;
        }
        ret = min(preDP[1], preDP[2]);

        int row = 1;

        while (row < size - 1)
        {
            int col = size - 1;
            while (col>row)
            {
                int a = INT_MAX;
                if (col == size - 1)
                {
                    a = row+1;
                }
                else
                {
                    a = curDP[col + 1];
                }
                int b = preDP[col];
                if (s[row] == s[col]) 
                {
                    if (col == size - 1)
                    {
                        curDP[col] = row;
                    }
                    else
                    {
                        curDP[col] = preDP[col + 1];
                    }    
                }
                else
                {
                    curDP[col] = min(a, b) + 1;
                }
                if (col == row + 1 || col == row + 2)
                {
                    ret = min(ret, curDP[col]);
                }        
                col--;                
            }
            preDP = curDP;
            curDP = tmpDP;
            row++;
        }

        return ret;
    }

  • 相关阅读:
    [《不敢说爱的年纪》小个子的小说集]2012年8月28日
    javascript数据类型
    Gateway+Oauth2授权码登录
    javascript为<a href=“#“>文字连接创建表单格式,后台菜单生成input表单
    操作系统(王道)
    【 云原生 | K8S 】kubeadm 部署Kubernetes集群
    2022-纯css3飞翔的小鸟
    枚举的应用
    CSP2022
    MMU如何通过虚拟地址找到物理地址-下
  • 原文地址:https://blog.csdn.net/yinhua405/article/details/126882960