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

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-insertion-steps-to-make-a-string-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

最长回文子序列

import java.util.Scanner;

class Solution {

    public static int minInsertions(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        int n = s.length();
        int[][] dp = new int[n][n];

        for (int i = 0; i < n; ++i) {
            dp[i][i] = 1;
        }

        for (int i = 1; i < n; ++i) {
            if (s.charAt(i - 1) == s.charAt(i)) {
                dp[i - 1][i] = 2;
            } else {
                dp[i - 1][i] = 1;
            }
        }

        for (int i = n - 2; i >= 0; --i) {
            for (int j = i + 2; j < n; ++j) {
                if (s.charAt(i) == s.charAt(j)) {
                    dp[i][j] = 2 + dp[i + 1][j - 1];
                } else {
                    dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
                }
            }
        }

        return n - dp[0][n - 1];
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(minInsertions(in.next()));
        }
    }
}

动态规划

import java.util.Scanner;

class Solution {

    public static int minInsertions(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        int n = s.length();
        int[][] dp = new int[n][n];

        for (int i = 0; i < n; ++i) {
            dp[i][i] = 0;
        }

        for (int i = 1; i < n; ++i) {
            if (s.charAt(i - 1) == s.charAt(i)) {
                dp[i - 1][i] = 0;
            } else {
                dp[i - 1][i] = 1;
            }
        }

        for (int i = n - 2; i >= 0; --i) {
            for (int j = i + 2; j < n; ++j) {
                if (s.charAt(i) == s.charAt(j)) {
                    dp[i][j] = dp[i + 1][j - 1];
                } else {
                    dp[i][j] = Math.min(dp[i + 1][j], dp[i][j - 1]) + 1;
                }
            }
        }

        return dp[0][n - 1];
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(minInsertions(in.next()));
        }
    }
}
上一篇:java--10正则表达式匹配


下一篇:DP动态规划之交错字符串