题目
BUPT 2016 计算机 ProblemB
给你一个01序列,HDLC协议处理的话,如果出现连续的5个1会补1个0。例如1111110,会变成11111010。
现在给你一个经过HDLC处理后的01序列,你需要找到HDLC处理之前的01序列。
例如给你11111010
你需要输出1111110
输入描述
输入正整数N,表示N例测试。接着输入N组数据,每组输入经过HDLC处理过的01序列(长度小于100)。
输出描述
对每组输入数据,输出HDLC处理前的01序列。
示例
输入
2
11111010
1111100
输出
1111110
111110
题解
法1:string库函数
最近做string的题有点魔怔了,看见string就想用库,但是其实这道题用库并不方便,用库的代码如下:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int n;
cin>>n;
string aft;
for(int i=0;i<n;i++){
cin>>aft;
int start=0;//记录截取的子串在整个aft中的起始位置
string temp=aft;//把删掉0前面子串删除之后剩余的串
int pos=aft.find("11111");
while(pos!=string::npos)
{
aft.erase(start+pos+5,1);
temp.erase(pos+5,1);
start+=pos+5;//更新temp在aft中的起始位置
temp=temp.substr(pos+5);//删掉遍历过的部分,形成新的子串
pos=temp.find("11111");//在新子串中找五个1的位置
}
cout<<aft<<endl;
}
}
有点混乱,权当熟悉库函数了吧
法2:遍历删‘0’
好想又好写,个人感觉就是最佳做法了
#include<iostream>
#include<string>
using namespace std;
int main()
{
int n;
cin>>n;
string aft;
for(int i=0;i<n;i++){
cin>>aft;
int count=0;
for(int j=0;j<aft.length();j++)
{
if(aft[j]=='1')
count++;
else
count=0;
//连续5个1,删除后面一个‘0’,count归零
if(count==5)
{
aft.erase(j+1,1);
count=0;
}
}
cout<<aft<<endl;
}
}