zoukankan      html  css  js  c++  java
  • 杭电21题 Palindrome

    Problem 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

    题意:输入一个字符串看,求最少加入多少个字符,使得字符串形成一个回文字符串;

    思路:

    AC代码:

     1 #include<iostream>
     2 #include<algorithm>
     3 #include<cstring>
     4 #include<string>
     5 #include<cstdio>
     6 #include<cmath>
     7 
     8 using namespace std;
     9 
    10 int main()
    11 {
    12     string str1,str2;
    13     int n;
    14     int dp[2][5010]={0};
    15     cin>>n>>str1;//输入n和字符串;
    16     int i,j;//循环变量;
    17     str2=str1;//扩展字符串str2;
    18     for(i=0;i<n;i++)
    19         str2[n-i-1]=str1[i];//将str1反序输入到str2中
    20     for(i=1;i<=n;i++)
    21     {
    22         for(j=1;j<=n;j++)
    23         {
    24             if(str1[i-1]==str2[j-1])dp[i%2][j]=dp[1-i%2][j-1]+1;//如果str1的第i个元素与str2第j个元素相同时,递归到dp[i-1][j-1]+1;
    25             else
    26             {
    27                 dp[i%2][j]=max(dp[1-i%2][j],dp[i%2][j-1]);//如果str1的第i个元素与str2第j个元素不同时
    28             }//递归dp[i-1][j]和dp[i][j-1]中比较大的递归到dp[i][j]
    29         }
    30     }
    31     cout<<n-dp[n%2][n]<<endl;
    32     return 0;
    33 }
    View Code
  • 相关阅读:
    周纪一
    太极拳_起势
    Guidelines for clock
    Linker scripts之MEMORY
    Linker scripts之SECTIONS
    Linker scripts之Intro
    潭州课堂25班:Ph201805201 爬虫基础 第十三课 cookie (课堂笔记)
    潭州课堂25班:Ph201805201 爬虫基础 第十二课 点触验证码二 (课堂笔记)
    潭州课堂25班:Ph201805201 爬虫基础 第十一课 点触验证码 (课堂笔记)
    潭州课堂25班:Ph201805201 爬虫基础 第十课 图像处理- 极验验证码 (课堂笔记)
  • 原文地址:https://www.cnblogs.com/zhangchengbing/p/3247511.html
Copyright © 2011-2022 走看看