给定一个字符串s,你可以从中删除一些字符,使得剩下的串是一个回文串。如何删除才能使得回文串最长呢?
输出需要删除的字符个数。
思路:将原字符串反转,求出元字符串与反转字符串最长公共子序列(也就是最长的回文串);
c++代码(网上搜的):

此处)折叠或打开


1. #include <bits/stdc++.h>
2. ;
3.  
4. const int MAXN=1010;
5. int dp[MAXN][MAXN];
6.  
7. class Solution
8. {
9. public:
10. int solve(string &s)
11. {
12. .length()-getLCS(s);
13. }
14.  
15. int getLCS(string &s1)
16. {
17. string s2(s1);
18. (s2.begin(),s2.end());
19. int len=s1.length();
20. (dp,0,sizeof dp);
21. for(int i=0;i<len;++i)
22. {
23. for(int j=0;j<len;++j)
24. {
25. if(s1[i]==s2[j])
26. [i+1][j+1]=dp[i][j]+1;
27. else dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);
28. }
29. }
30. [len][len];
31. }
32. };
33.  
34. int main()
35. {
36. string s;
37. while(cin>>s)
38. {
39. ;
40. <<solution.solve(s)<<endl;
41. }
42. ;
43. }



c语言代码:


此处)折叠或打开


1. #include<stdio.h>
2. <stdlib.h>
3. <string.h>
4. (char *str,int from,int to)
5. {
6. while (from < to)
7. {
8. = str[from];
9. [from++] = str[to];
10. [to--] = temp;
11. }
12. }
13. int getLcs(char *str1,char *str2,int length)
14. {
15. //printf("%s %s\n",str1,str2);//居然是一样的
16. int dp[length][length];
17. int i =0,j = 0;
18. for (i = 0;i <length;i++)
19. {
20. for (j = 0;j < length;j++)
21. [i][j] = 0;
22. }
23. //    int i = 0,j = 0;
24. for (i = 0;i < length;i++)
25. {
26. for (j = 0;j < length;j++)
27. {
28. if (i == 0 || j == 0)
29. {
30. if (str1[i] == str2[j])
31. {
32. [i][j] = 1;
33. }
34. else
35. {
36. if (i > 0)
37. [i][j] = dp[i-1][j];
38. if (j > 0)
39. [i][j] = dp[i][j-1];
40. }
41. }
42. else if (str1[i] == str2[j])
43. {
44. [i][j] = dp[i-1][j-1]+1;
45. }
46. else {
47. [i][j] = ((dp[i-1][j] > dp[i][j-1]) ?dp[i-1][j]:dp[i][j-1]);
48. }
49. }
50. }
51. [length-1][length-1];
52. }
53. int main()
54. {
55. [1024];//注意下字符串指针
56. //char *str1 = "abcda";
57. //char *str2 = "adcba";
58.      
59. while (gets(str))
60. {
61. int len = strlen(str);
62. [1024];
63. //    char *str1 = str;
64. //    printf("str1 = %s\n",str1);
65.          
66. (str1,str);
67. (str,0,len-1);
68.  
69.          
70. //printf("str2 = %s\n",str2);
71. int result = getLcs(str1,str,len);
72.  
73. ("%d\n",(len-result));
74. //free(str2);
75. }
76. ;
77. //getLcs()
78.      
79. }
80.  
81.