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

来源:互联网 发布:啪啪啪软件下载 编辑:程序博客网 时间:2024/04/30 02:52

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;}


0 0