zoukankan      html  css  js  c++  java
  • Palindrome

    Description

    A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome.
    As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome.
     

    Input

    Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from 'A' to 'Z', lowercase letters from 'a' to 'z' and digits from '0' to '9'. Uppercase and lowercase letters are to be considered distinct.
     

    Output

    Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.
     

    Sample Input

    5 Ab3bd
     

    Sample Output

    2
     
    插入几个字符使原本的串成为回文串
    View Code
     1 #include<stdio.h>
    2 #include<stdlib.h>
    3 #include<math.h>
    4 #include<string.h>
    5 char str[5010], str1[5010];
    6 int dp[3][5010];
    7
    8 int max( int x, int y )
    9 {
    10 return x>y?x:y;
    11 }
    12
    13 int main()
    14 {
    15 int n, k;
    16 while( scanf( "%d", &n ) == 1 )
    17 {
    18 scanf( "%s", str );
    19 k = 0;
    20 for( int i = n-1; i >= 0; i-- )
    21 str1[k++] = str[i];
    22 memset( dp, 0, sizeof(dp) );
    23 for( int i = 0; i < n; i++ )
    24 for( int j = 0; j < k; j++ )
    25 {
    26 if( str[i] == str1[j] )
    27 dp[(i+1)%2][j+1] = dp[i%2][j]+1;
    28 else
    29 {
    30 dp[(i+1)%2][j+1] = max(dp[i%2][j+1],dp[(i+1)%2][j]);
    31 }
    32 }
    33 printf( "%d\n", n-dp[n%2][k]);
    34 }
    35 }

  • 相关阅读:
    Networking
    Table of Contents
    Table of Contents
    Jersey(1.19.1)
    Jersey(1.19.1)
    11.Container With Most Water---两指针
    85.Maximal Rectangle---dp
    42.Trapping Rain Water---dp,stack,两指针
    84.Largest Rectangle in histogram---stack
    174.Dungeon Game---dp
  • 原文地址:https://www.cnblogs.com/zsj576637357/p/2423240.html
Copyright © 2011-2022 走看看