您的位置:首页 > 其它

可删除某些字符的最长回文字符串(2016腾讯在线笔试题)

2016-05-18 20:45 851 查看
可转载,请附上原链接

输入:amka时,删除字符m可以得到最长回文字符串aka,则输出3

输入:abcddcka,删除b和k时,acddca是最长回文字符串,输出6

思路:用两个指针,一个指向字符串一个字符,一个指向字符串最后一个字符,

如果两个字符串相等,如abcda,时就进行递归看bcd中的最长回文字符串

如果不想等,就找abcd,和bcda中的最长回文字符串

对于递归的公共子问题,用动态规划解决

程序如下:

#include"stdafx.h"
#include<iostream>
#include<stdlib.h>
#include<stdio.h>

using namespace std;

int Length_record[1000][1000];

int max(int a, int b)
{
return a > b ? a : b;
}

int number_of_reverse(char* str, int start, int end, int crruentLength, int &max_Length)
{
if (Length_record[start][end] != -1)
{
if (crruentLength + Length_record[start][end] > max_Length)
max_Length = crruentLength + Length_record[start][end];
return Length_record[start][end];
}
if (Length_record[start][end] == -1)
{
if (start == end)
{
crruentLength++;
if (crruentLength > max_Length)
max_Length = crruentLength;
Length_record[start][end] = 1;
}
if (end - start == 1)
{
if (str[start] == str[end])
{
crruentLength += 2;
Length_record[start][end] = 2;
}
else
{
crruentLength++;
Length_record[start][end] = 1;
}
if (crruentLength > max_Length)
max_Length = crruentLength;
}
if (end - start > 1)
{
if (str[end] == str[start])
Length_record[start][end]=2+number_of_reverse(str, start + 1, end - 1, crruentLength + 2, max_Length);
else
{
Length_record[start][end] =max( number_of_reverse(str, start, end - 1, crruentLength, max_Length), number_of_reverse(str, start + 1, end, crruentLength, max_Length));
}
}
}
return Length_record[start][end];

}

int number_of_delete(char *str)
{
if (str == NULL)
cout << "0" << endl;
int nLength = strlen(str);
int max_Length = 0;
number_of_reverse(str, 0, nLength - 1, 0, max_Length);
return max_Length;
}

int main()
{
memset(Length_record, -1, sizeof(Length_record));
char str[1000];
cin >> str;
int a = number_of_delete(str);
cout << a << endl;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: