您的位置:首页 > 其它

去掉字符串中连续出现k个0的字串

2016-08-13 14:55 211 查看
A000B0000  K=3    ----->     AB0000

这里注意一下:

当循环结束后,要检查下count是否等于k,如果不等于k,要把s后面的补回去

//
// main.cpp
// 去掉字符串中连续出现k个0的字串
//
// Created by zjl on 16/8/13.
// Copyright © 2016年 zjl. All rights reserved.
// A0000B000 A0000B

#include <iostream>
#include <string>
using namespace std;

void solve(string& s, int k){
int pos = -1, count = 0;
int len = s.size();
for(int i = 0; i < s.size(); i++){
if(s[i] == '0')
count++;
else{
if(count == k || count == 0){
s[++pos] = s[i];
}else{
while(count){
s[++pos] = s[i - count];
count--;
}
s[++pos] = s[i];
}
count = 0;
}
}
if(count != k && count > 0){
while(count--)
s[++pos] = s[ len - 1 - count];
}

s = s.substr(0, pos+1);
}

int main(int argc, const char * argv[]) {
// insert code here...
string s = "A0000B0000";
solve(s, 3);
cout << s<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string