首页 新闻 会员 周边

回文字符串!

0
悬赏园豆:5 [已关闭问题] 关闭于 2016-07-25 13:20
回文字符串
难度级别: A; 编程语言:不限;运行时间限制:1000ms; 运行空间限制:256000KB; 代码长度限制:2000000B
试题描述

    给定一个字符串 S ,最少需要几次增删改操作可以把 S 变成一个回文字符串?一次操作可以在任意位置插入一个字符,或者删除任意一个字符,或者把任意一个字符修改成任意其他字符。

输入
字符串 S,只包含'A'-'Z'。
输出
最少的修改次数。
输入示例
ABAD
输出示例
1
其他说明
对于100%的数据,S的长度不超过100。
LZHEHE的主页 LZHEHE | 菜鸟二级 | 园豆:202
提问于:2016-07-25 09:31
< >
分享
所有回答(1)
-1

参考:http://blog.csdn.net/sdjzping/article/details/12151687

 1 public class Palindrome
 2     {
 3         public char[] str;
 4         public int[,] visit;
 5         public int[,] dp;  
 6         public Palindrome(string s)
 7         {
 8             str = s.ToCharArray();
 9             visit = new int[s.Length,s.Length];
10             dp = new int[s.Length,s.Length];
11             for (int i = 0; i < s.Length - 1; i++)
12             {
13                 for (int j = 0; j < s.Length - 1; j++)
14                 {
15                     visit[i,j] = 0;
16                     dp[i,j] = 0;
17                 }
18             } 
19         }
20         public int DP(int x, int y)
21         {
22             if (visit[x,y] == 1)
23                 return dp[x,y];
24             else if (x >= y)
25             {
26                 visit[x,y] = 1;
27                 dp[x,y] = 0;
28                 return 0;
29             }
30             else
31             {
32                 if (str[x] == str[y])
33                 {
34                     dp[x,y] = DP(x + 1, y - 1);
35                     visit[x,y] = 1;
36                     return dp[x,y];  
37                 }
38                 else
39                 {
40                     dp[x,y] = 1 + Math.Min(Math.Min(DP(x + 1, y), DP(x, y - 1)), DP(x + 1, y - 1));
41                     visit[x,y] = 1;
42                     return dp[x,y];
43                 }
44             }
45         } 
46 
47         public static void test(string s , out int dp)
48         {
49             Palindrome pld = new Palindrome(s);
50             dp = pld.DP(0, s.Length - 1);
51         }
52     }

 

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             while(true)
 6             {
 7                 Console.WriteLine("请输入字符串:");
 8                 string s = Console.ReadLine();
 9                 int dp = 0;
10                 Palindrome.test(s, out dp);
11                 Console.WriteLine(dp);
12             }            
13         }
14     }

clarlespeng | 园豆:469 (菜鸟二级) | 2016-07-25 11:37
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册