您的位置:首页 > 编程语言 > C语言/C++

C++实现去掉字符串中连续相同K个0子串

2017-07-11 11:09 567 查看
题目:给定一个字符串和str和一个整数k,把字符串中有连续0的子串去除

#include <iostream>
#include <string>

using namespace std;

string deleteSeriesZero(string str,int k)
{
if (!str.size())
return NULL;
int i = 0;
int count ;//统计每一个子串0的个数
int flag =0;//新串的标记位置

while (i<str.size())//循环遍历每一个字符
{
count = 0;
while (i<str.size() && str[i] != '0')//字符不为0往后移一位
{
str[flag++] = str[i++];

}

while (i<str.size() && str[i] == '0')//字符为0加1
{
count++;
i++;

}
if (count==k)//找到满足子串,flag往后移一位
{
str[flag++] = str[i++];
}
else//0子串不满足k则往后移动count位并记录每位字符值
{
for (int j = i - count; j <=i; j++)
{
str[flag++] = str[j];
}
i++;
}

}
return str.substr(0, flag);//返回所求子串

}

int main()

{
string str1 = "A000B00C00D";
string str2 = "000A00B0000C000";
string result1 = deleteSeriesZero(str1,2);
string result2 = deleteSeriesZero(str2, 3);
cout << "A000B00C00D的结果是:" << result1 << endl << "000A00B0000C000的结果是:" << result2<< endl;;
cin.get();
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: