题目:http://hihocoder.com/problemset/problem/1039

给定一个字符串s,只包含'A', 'B', 'C'三种字符

1. 向 s 的任意位置 (包括头和尾) 中插入'A', 'B', 'C'中任意一个字符

2. 递归删除 s 中的相同字符,要求第1步的插入位置使得消除的字符最多

递归删除: "ABCCBCCCAA"->"ABB"->"A'

思路

1. 枚举:向 s 中插入一个字符获得新字符串s', 计算s' 可以删除的字符

2. 递归删除

  • stack<Segment>存储每次可以删除的位置。利用先进后出,在删除的时候不用重新计算位置

源码

 #include <string>
#include <stack>
#include <iostream>
using namespace std; struct Segment
{
Segment(int _s, int _e){ start = _s; end = _e; }
int start;
int end;
}; int remove(string& str)
{
stack<Segment> segments;
int i, j, strLen, score;
i = , j = , score = ;
strLen = str.length();
while (j < strLen)
{
if (str[i] == str[j])
++j;
if (j >= strLen || str[i] != str[j])
{
if (j - i > )
segments.push(Segment(i, j));
i = j;
j = i + ; }
if (j >= strLen)
{
if (segments.empty())
break;
while (!segments.empty())
{
Segment tmp = segments.top();
segments.pop();
str.erase(str.begin() + tmp.start, str.begin() + tmp.end);
score = score + tmp.end - tmp.start;
}
i = ;
j = ;
strLen = str.length();
}
}
return score;
}
int main()
{
int cnt, strLen, i, j, score;
string str; cin >> cnt;
while (cnt-- > )
{
cin >> str;
score = ;
strLen = str.length();
for (i = ; i < strLen; i++)
{
for (char cha = 'A'; cha <= 'C'; cha++){
string tmp = str;
tmp.insert(i, &cha);
j = remove(tmp);
if (j > score)
score = j;
}
}
cout << score<< endl;
}
return ;
}

最新文章

  1. BPM SharePoint解决方案分享
  2. linux的三种安装软件包的方式(小白的学习之旅)
  3. Javascript软键盘设计
  4. PHP--Warning: Invalid argument supplied for foreach() in ...
  5. 20155226田皓宇关于优秀技能经验以及c语言学习感悟和对JAVA的展望
  6. Perl Debug error: SetConsoleMode failed, LastError=|6|
  7. AP_HZ Party和Supplier、Bank表关系详解
  8. C和C++头文件的不同
  9. Lintcode--007(不同的子序列)
  10. 在WPF中使用AForge.net控制摄像头拍照
  11. java基础练习 7
  12. 【其他】MySql常用命令
  13. Oracle 11g OCM 考试大纲
  14. Zabbix (三)
  15. socket实现FTP上传下载功能
  16. MyBatis 多表关联查询
  17. lua闭包实现迭代器遍历数组
  18. 【iOS XMPP】使用XMPPFramewok(一):添加XMPPFramework(XCode 4.6.2)
  19. python3模块: json &amp; pickle
  20. jsp数据库连接大全和数据库操作封装到Javabean

热门文章

  1. SameSite Cookie,防止 CSRF 攻击
  2. (转载)JavaWeb学习总结(五十一)——邮件的发送与接收原理
  3. Apple Watch版微信来了 收发微信刷朋友圈不在话下
  4. DPM算法源程序voc-release5在Windows中的配置修改过程
  5. centos7.0安装后ifconfig无法使用
  6. 解决SprngMVC中ResponseBody注解中文乱码
  7. js: 从setTimeout说事件循环模型
  8. Gym - 101102B
  9. VIM退出命令
  10. C#回顾 - 8.利用反射动态创建对象