zoukankan      html  css  js  c++  java
  • 构造回文

    题目:
    这里写图片描述

    思路:把原序列和原序列的反序列做比较,求最大共同子串(DP),然后用原长度减去共同子串的长度,即可得出原序列;

    例如:abcda 做DP

         0 1 2 3 4 5
    
      0  0 0 0 0 0 0
      1  0 1 1 1 1 1
      2  0 1 1 1 2 2
      3  0 1 1 2 2 2
      4  0 1 2 2 2 2
      5  0 2 2 2 2 3
    

    求出最大相同的代码如上为 int[5][5]=3;

    实现AC代码如下:

    import java.util.Scanner;
    
    /**
     * Created by yan on 2016/9/11.
     */
    public class Main2 {
    
        public static void main(String[] args){
            Scanner in = new Scanner(System.in);
            while (in.hasNext()){
                String str  = in.next();
                char[] chars= str.toCharArray();
                int length  = str.length();
                int[][] dp = new int[length+1][length+1];
                //dp
                for(int i=0;i<length;i++){
                    for(int j=0;j<length;j++){
                        if(chars[i]==chars[length-j-1]){
                            dp[i+1][j+1] = dp[i][j]+1;
                         }else{
                            dp[i+1][j+1] = (Math.max(dp[i+1][j],dp[i][j+1]))>dp[i][j]?Math.max(dp[i+1][j],dp[i][j+1]):dp[i][j];
                        }
                    }
                }
                System.out.println(length-dp[length][length]);
            }
        }
    
    
    }

    在牛客网上可以完美AC,根据这么多天失败的经历,要注意输出的格式,注意换行,注意是否有多余的空格。

  • 相关阅读:
    phpcms 短信替换
    phpcms 搭建宣传网站首页
    JDK 8
    MySQL 5.6 date 与 string 的转换和比较
    Illustration of Git branching and merge
    Anti-pattern(反模式)
    Design Patterns笔记
    MyBatis小抄
    MyBatis MapperScannerConfigurer
    MyBatis 批量插入数据对插入记录数的限制
  • 原文地址:https://www.cnblogs.com/yankang/p/6399020.html
Copyright © 2011-2022 走看看