给你一个只有0和1的字符串,你现在有一个操作,可以把相邻的一对0和1消去,问最后能得到的最短长度...

题目描述:

给你一个只有0和1的字符串,你现在有一个操作,可以把相邻的一对0和1消去,问最后能得到的最短长度。

输入描述:

一个整数(表示01字符串长度)和一个01字符串。

输出描述:

最后得到的最短长度。

方法1:

分析:

如果相邻两元素的和是1(包含了“01”和“10”两种情况),则将这一对元素删除掉,并改变遍历索引,继续向后遍历。

代码:

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 void main()
 6 {
 7     int nLength = 0;    // 01字符串长度
 8     string str0And1;    // 01字符串
 9     cin >> nLength;
10     cin >> str0And1;
11     unsigned int i = 0;
12     while (i < str0And1.size() - 1){
13         if (str0And1[i] + str0And1[i + 1] == 0x61){
14             str0And1.erase(i, 2);            // 移除01
15             // 字符串为空或只有一个元素,则跳出并结束搜索
16             if (str0And1.size() < 2)
17                 break;
18             // 若i>0,则向后退一步,若i=0,则保持
19             if (i > 0)
20                 i -= 1;
21         }
22         else
23             i++;    // 向后继续搜索
24     }
25     cout << str0And1.size() << endl;
26     system("pause");
27 }

方法2:

分析:

从一个含有0或1的字符串到只含有0或只含有1或为空的字符串,中间发生了0-1的相消,那么最终剩下的是0还是1,还是空呢,就要看0和1的个数啦!

先交一波智商税。。。

代码:

 1 #include <iostream>
 2 #include <string>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 void main()
 7 {
 8     int nLength = 0;        // 01字符串长度
 9     string str0And1;        // 01字符串
10     unsigned int num0 = 0;    // 0的个数
11     unsigned int num1 = 0;    // 1的个数
12     cin >> nLength;
13     cin >> str0And1;
14     for (unsigned int i = 0; i < str0And1.size(); i++)
15     {
16         if (str0And1[i] == 0x30)
17             num0++;
18         else
19             num1++;
20     }
21     cout << nLength - min(num0, num1) * 2 << endl;
22     system("pause");
23 }

总结:

显然方法二更美妙。换个角度思考问题,别搞得太复杂。

转载于:https://www.cnblogs.com/garrettlu/p/10665371.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值