赞
踩
import java.util.Scanner; public class 回文串_动态规划 { public static void main(String[] args) { String s; Scanner scanner=new Scanner(System.in); s=scanner.next(); System.out.println(minInsertions(s)); } public static int minInsertions(String s) { int n = s.length(); char []arry=new char[n]; arry=s.toCharArray(); int []dp=new int[n]; int temp = 0; for (int i = n - 2; i >= 0; i--) { // 记录 dp[i+1][j-1] int pre = 0; for (int j = i + 1; j < n; j++) { temp = dp[j]; if (arry[i] == arry[j]) { // dp[i][j] = dp[i+1][j-1]; dp[j] = pre; } else { // dp[i][j] = min(dp[i+1][j], dp[i][j-1]) + 1; dp[j] =Math.min(dp[j], dp[j - 1]) + 1; } pre = temp; } } return dp[n - 1]; } }
参考了这位博主的文章https://blog.csdn.net/weixin_39914868/article/details/114280581
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。