经典笔试题——去掉字符串中连续出现K个0的子串

  1. 去掉字符串中连续出现K0的子串

【题目】给定一个字符串str和一个整数k,如果str中正好有连续的k0’字符出现时,把k个连续的0’字符去除,返回处理后的字符串。

【例如】str=”A00B”k=2,结果为AB;

str=”A0000B000”,K=3, 结果为A0000B”


 

1 #include<iostream>
  2 #include<string>
  3 using namespace std;
  4 int main()
  5 {
  6     cout<<"str=";
  7     string str;
  8     cin>>str;
  9     int k;
 10     cout<<"k=";
 11     cin>>k;
 12     int len = str.size();
 13     int i, count = 0;
 14     string new_str;
 15     if(k == 0 || len == 0)
 16     {
 17         cout<<str;
 18         return 0;
 19     }   
 20     for(i=0; i<len; i++)
 21     {
 22         if(str[i] == '0')
 23             count++;
 24         else
 25         {
 26             if(count != k)
 27                 new_str += str.substr(i-count, count+1);//str.substr(i-count, count+1)是从i-count(此为原来str 的下标中)开始复制到new_str中总共复制count+1个数
 28             else
 29                 new_str += str[i];
 30             count = 0;
 31         }   
 32     }
 33     cout<<new_str<<endl;
 34     return 0;
 35 }   


实例:输入:str = A00B000A0000B00A0B00AB

                            k  =  2

  输出:AB000A0000BA0BAB


猜你喜欢

转载自blog.csdn.net/csdn_wanziooo/article/details/77000034
今日推荐