• 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;
    }

  • 相关阅读:
    C专家编程 第6章 运行的诗章:运行时数据结构 6.11 有用的C语言工具
    勒索病毒最新变种.halo勒索病毒来袭,如何恢复受感染的数据?
    PMP-第二章-项目运作环境
    【学习笔记41】DOM操作的练习
    java计算机毕业设计线上家庭医生系统设计与实现MyBatis+系统+LW文档+源码+调试部署
    公众号如何获取视频号下载工具?
    单调栈 单调队列 尺取法
    prometheus学习1部署了解
    Keras CIFAR-10分类 SVM 分类器篇
    php农校通系统mysql家校通
  • 原文地址:https://blog.csdn.net/yinhua405/article/details/126882960