Another Problem on Strings(sdau19训练)

【Question】

A string is binary, if it consists only of characters “0” and “1”.
String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string “010” has six substrings: “0”, “1”, “0”, “01”, “10”, “010”. Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.
You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters “1”.

【Input】

The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.

【Output】

Print the single number — the number of substrings of the given string, containing exactly k characters “1”.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

【Examples】

Input1

1
1010

Output1

6

Input2

2
01010

Output2

4

Input3

100
01010

Output3

0

【Note】

In the first sample the sought substrings are: “1”, “1”, “10”, “01”, “10”, “010”.
In the second sample the sought substrings are: “101”, “0101”, “1010”, “01010”.

【思路】

题意:给定一个只包含1和0的串,问其中恰好包含k个1的字串的个数
话说这道题题解真的巧妙,想不到……看了半天才弄懂了
看代码,有注释

【源代码】

#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;
int num[1000010];
int main()
{
 long long int ans=0;
 int k;
 cin >> k;
 string s;
 cin >> s;
 num[0]=1;//num[i]里面存的数表示从串首开始恰好有i个1的串的个数。
 int mid=0;
 for(int i=0;i<s.length();i++)
 { //num[cnt-k]就是当前已经出现的1的总个数减去要求的个数,
  if(s[i]=='1')
   mid++;
  if(mid>=k)
   ans+=num[mid-k];
   /*这里为什么这么写呢
     在遇见下一个1之前,含第i位字串的数目就等于该位本身到前一位1的数字的个数
     举个例子,1010,当在第0位时,就此一位;但i=1时,包含该位的含1的字串数目就等于1,此时ans=1+1=2
     i=2时,又遇见1,mid+1后,此时看前一位1后面有几位数即字串个数;
     i=3时,含该位的字串为01,010两种,即该位到前一位1的数字的数量
          */
  num[mid]++;//累计第i个1后面0的个数+1本身
 }
 cout << ans <<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浅梦曾倾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值