题目要求
题目详情
给定一个字符串,仅由a,b,c 3种小写字母组成。当出现连续两个不同的字母时,你可以用另外一个字母替换它,如
- 有ab或ba连续出现,你把它们替换为字母c;
- 有ac或ca连续出现时,你可以把它们替换为字母b;
- 有bc或cb 连续出现时,你可以把它们替换为字母a。
你可以不断反复按照这个规则进行替换,你的目标是使得最终结果所得到的字符串尽可能短,求最终结果的最短长度。
输入:字符串。长度不超过200,仅由abc三种小写字母组成。
输出: 按照上述规则不断消除替换,所得到的字符串最短的长度。
例如:
输入cab,输出2。因为我们可以把它变为bb或者变为cc。
输入bcab,输出1。尽管我们可以把它变为aab -> ac -> b,也可以把它变为bbb,但因为前者长度更短,所以输出1。
http://hero.pongo.cn/Question/Details?ID=85&ExamID=83
分析求解
可以采用DP方法求解:
设dp[i,j]表示字符串从第i个到第j个经过字符消除后所剩余的字母个数。
则dp[1,lengh]则为最终的结果。
按照要求,所剩余的字母一定是单一的一种,如果是多种就可以继续消除了。
因此还需要一个与dp同样大小的数组记录第i到第j所剩余的字母,store[i, j]。
递推公式是:
dp[i, j] = min{solve(dp[i, k], dp[k, j]), (i<=k<=j)}
solve函数是根据dp[i, k]和dp[k,j]的数值与store[i,k]和store[k,j]所记录的字母计算经过消除后的结果。
整个过程中solve函数处理比较麻烦,考虑的情况比较多。
例如:
bcab
dp[i,j]为
代码
#define NUM 200
char store[NUM + 1][NUM + 1];
int dp[NUM + 1][NUM + 1];
const int value= 'a' + 'b' + 'c';
int solve(const char *s, int i1, int j1, int i2, int j2, char *letter)
{
char letter1 = store[i1][j1];
char letter2 = store[i2][j2];
int res;
if(letter1 == letter2)//如果相等那么直接相加
{
*letter = letter1;
res = dp[i1][j1] + dp[i2][j2];
}
else
{
if(dp[i1][j1] % 2 == 0 && dp[i2][j2] % 2 == 0)//如果两个字符不一样且个数都是偶数,可以推出一定剩余两个字符,并选定第一个作为结果
{
*letter = letter1;
res = 2;
}
else
{
int cntmax;
int cntmin;
char tmp;
char tmp2;
char tmp3;
if(dp[i1][j1] >= dp[i2][j2])//考考虑到两个字符个数可能都超过1时要计算消除后的结果
{
cntmax = dp[i1][j1];
cntmin = dp[i2][j2];
tmp = letter1;
tmp2 = letter2;
}
else
{
cntmin = dp[i1][j1];
cntmax = dp[i2][j2];
tmp = letter2;
tmp2 = letter1;
}
tmp3 = tmp2;
for(int i = 0; i < cntmax; ++i)//先计算字符个数多的,如aaaabbb,先计算消除a,再计算消除b
{
tmp2 = value - tmp - tmp2;
}
for(int i = 1; i < cntmin; ++i)//再计算字符个数少的
{
tmp2 = value - tmp3 - tmp2;
}
*letter = tmp2;
res = 1;
}
}
return res;
}
int minLength(const char *s)
{
int lengh = strlen(s);
memset(dp, 0, sizeof(dp));
memset(store, 0, sizeof(store));
//初始化dp和store,起始时只有对角线上有数据,且每个都是1
for(int i = 1; i <= lengh; ++i)
{
dp[i][i] = 1;
store[i][i] = s[i - 1];
}
for(int j = 2; j <= lengh; ++j)
{
for(int i = j - 1; i > 0; --i)//从后向前计算,因为第i的结果是基于i之后字符串的
{
char ctmp;
int min = solve(s, i, i, i + 1, j, &ctmp);
for(int tmp = i + 1; tmp < j; ++tmp) //计算从i到j中i-k与k+1-j为第小的
{
char ctmp2;
int mintmp = solve(s, i, tmp, tmp + 1, j, &ctmp2);
if(min > mintmp)
{
min = mintmp;
ctmp = ctmp2;
}
}
dp[i][j] = min;
store[i][j] = ctmp;
}
}
//记录动态规划过程
FILE *pfile;
pfile = fopen("1.txt", "w");
for(int i = 1; i <= lengh; ++i)
{
for(int j = 1; j <= lengh; ++j)
{
fprintf(pfile, "%d", dp[i][j]);
}
fprintf(pfile, "\n");
}
for(int i = 1; i <= lengh; ++i)
{
for(int j = 1; j <= lengh; ++j)
{
fprintf(pfile, "%c", store[i][j]);
}
fprintf(pfile, "\n");
}
fclose(pfile);
return dp[1][lengh];
}
测试
1.bcab
2.bbaaaacc
3.abcabcabc
PS:后来看别人做的,感觉自己想的比较麻烦