[hihoCoder]#1039 : 字符消除

Description

小Hi最近在玩一个字符消除游戏。给定一个只包含大写字母"ABC"的字符串s,消除过程是如下进行的:

1)如果s包含长度超过1的由相同字母组成的子串,那么这些子串会被同时消除,余下的子串拼成新的字符串。例如"ABCCBCCCAA"中"CC","CCC"和"AA"会被同时消除,余下"AB"和"B"拼成新的字符串"ABB"。

2)上述消除会反复一轮一轮进行,直到新的字符串不包含相邻的相同字符为止。例如”ABCCBCCCAA”经过一轮消除得到"ABB",再经过一轮消除得到"A"

游戏中的每一关小Hi都会面对一个字符串s。在消除开始前小Hi有机会在s中任意位置(第一个字符之前、最后一个字符之后以及相邻两个字符之间)插入任意一个字符('A','B'或者'C'),得到字符串t。t经过一系列消除后,小Hi的得分是消除掉的字符的总数。

请帮助小Hi计算要如何插入字符,才能获得最高得分。

Sample Input

3
ABCBCCCAA
AAA
ABC

Sample Output

9
4
2


自己写的代码,运行AC。
 1 #include <iostream>
 2 #include <string>
 3 #include <stdio.h>
 4 using namespace std;
 5 
 6 int EatLetter(char* word,char* newWord);
 7 int EliminateWord(char* word);
 8 void InputLetter(char* word,char* newWord,char c,int loc);
 9 int StartWork(char* word);
10 
11 int main()
12 { 
13     /*
14     freopen("data.txt","r",stdin);
15     freopen("out.txt","w",stdout);
16     */
17 
18     int round;
19     cin>>round;
20     for(int i=0;i<round;i++)
21     {
22         char* k=new char[100];
23         cin>>k;
24         cout<<StartWork(k)<<endl;
25         delete[] k;
26     }
27 
28     /*
29     fclose(stdin);
30     fclose(stdout);
31     */
32 }
33 
34 int EatLetter(char* word,char* newWord)
35 {
36     char temp;
37     int index=0;
38     int len=strlen(word);
39     for(int i=0;i<len;i++)
40     {
41         temp=word[i];
42         bool isSingle=true;
43         while(temp==word[i+1]&&i<len)
44         {
45             i++;
46             isSingle=false;
47         }
48         if(isSingle)
49             newWord[index++]=temp;
50     }
51     newWord[index]='';
52     return len-index;
53 }
54 
55 int EliminateWord(char* word)
56 {
57     int count=0;
58     int m=0;
59     while(m=EatLetter(word,word))
60     {
61         count+=m;
62     }
63     return count;
64 }
65 
66 void InputLetter(char* word,char* newWord,char c,int loc)
67 {
68     int len=strlen(word);
69     int index=0;
70     for(int i=0;i<len+1;i++)
71     {
72         if(i==loc)
73             newWord[index++]=c;
74         newWord[index++]=word[i];
75     }
76 }
77 
78 int StartWork(char* word)
79 {
80     int count=0;
81     char* newWord=new char[strlen(word)+2];
82     for(int i=0;i<strlen(word)+1;i++)
83     {
84         for(int j='A';j<='C';j++)
85         {
86         InputLetter(word,newWord,(char)j,i);
87         int temp=EliminateWord(newWord);
88         count=count>temp?count:temp;
89         }
90     }
91     return count;
92 }
原文地址:https://www.cnblogs.com/lsr-flying/p/4488527.html