给定一个字符串,仅由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。 函数头部: C/C++ int minLength(const char *s); Java: public class Main { public static int minLength(String s); }
#include <iostream>
using namespace std;
class Node
{
public:
Node(int v)
{
value = v;
next = NULL;
}
int value;
Node *next;
};
int minLength(const char *s)
{
Node *head = NULL;
Node *p = NULL;
Node *prev = NULL;
int size = 0;
while (*s != '\0')
{
switch (*s)
{
case 'a':
if (head == NULL)
{
head = new Node(1);
p = head;
}
else
{
p = new Node(1);
}
break;
case 'b':
if (head == NULL)
{
head = new Node(2);
p = head;
}
else
{
p = new Node(2);
}
break;
case 'c':
if (head == NULL)
{
head = new Node(4);
p = head;
}
else
{
p = new Node(4);
}
break;
default:
break;
}
if (prev != NULL)
{
prev->next = p;
prev = p;
}
else
{
prev = p;
}
s++;
size++;
}
int base = 7;
bool label = true;
int pos = 1;
while (label)
{
pos = 1;
label = false;
p = head;
while (size-pos >= 3)
{
if (p->value != p->next->value)
{
label = true;
Node *first = p;
Node *second = first->next;
Node *third = second->next;
Node *fourth = third->next;
if ((third->value == first->value)
|| (third->value == second->value))
{
first->value = base ^ (first->value) ^ (second->value);
first->next = third;
delete second;
size--;
}
else if (first->value == fourth->value)
{
first->value = base ^ (first->value) ^ (second->value);
first->next = third;
delete second;
size--;
}
else
{
second->value = base ^ (second->value) ^ (third->value);
second->next = fourth;
delete third;
p = second;
pos++;
size--;
}
}
else
{
pos++;
p = p->next;
}
}
if (pos == size)
{
break;
}
else if (pos+1 == size)
{
if (p->value == p->next->value)
{
break;
}
else
{
p->value = base ^ (p->value) ^ (p->next->value);
delete p->next;
p->next = NULL;
size--;
label = true;
}
}
else if (pos+2 == size)
{
Node *first = p;
Node *second = p->next;
Node *third = second->next;
if (first->value == second->value)
{
if (second->value == third->value)
{
break;
}
else
{
second->value = base ^ (second->value) ^ (third->value);
second->next = NULL;
delete third;
size--;
label = true;
}
}
else
{
first->value = base ^ (first->value) ^ (second->value);
first->next = third;
delete second;
size--;
label = true;
}
}
}
p = head;
while (p)
{
Node *temp = p->next;
delete p;
p = temp;
}
return size;
}
int main()
{
char s[] = "caacacaabcaaaccbbaabbaababcaaacabaacaaacaaabaaacbbacaacbabcaccbbbcbbabbbcbaacbcbcbbabaccccbbbaacabcaabbaacbcababccbccabcccccaccacbbaaabaacabbbaaabcbabaabccbaabccbaabcacbbaaaacaabcaaaacabbbbbbbccbbbaaa";
cout << minLength(s) << endl;
return 0;
}