博客
关于我
LeetCode 1573. 分割字符串的方案数(组合数学)
阅读量:216 次
发布时间:2019-03-01

本文共 1231 字,大约阅读时间需要 4 分钟。

题意:

给你一个二进制串 s  (一个只包含 0 和 1 的字符串),我们可以将 s 分割成 3 个 非空 字符串 s1, s2, s3 (s1 + s2 + s3 = s)。请你返回分割 s 的方案数,满足 s1,s2 和 s3 中字符 '1' 的数目相同。由于答案可能很大,请将它对 10^9 + 7 取余后返回。数据范围:s[i] == '0' 或者 s[i] == '1'3 <= s.length <= 10^5

解法:

设tot为1的总数量,如果tot=0,那么答案为C(n-1,2),如果tot!=0,那么:设串下标为[1,n],找到满足s[1,l]=tot/3的最小下标l,找到满足s[r,n]=tot/3的最大下标r,然后统计l+1开始到其右边第一个1之间0的数量cntl,以及r-1开始到其左边第一个1之间0的数量cntr.那么答案为(cntl+1)*(cntr+1),因为左边有cntl+1个空隙可以选择,右边有cntr+1个空隙可以选择.如下图:

在这里插入图片描述

code:

class Solution {   public:    static const int maxm=1e5+5;    static const int mod=1e9+7;    int d[maxm];    int numWays(string s) {           memset(d,0,sizeof d);        int n=s.size();        s='p'+s;        int ans=0;        for(int i=1;i<=n;i++){               d[i]=d[i-1]+(s[i]=='1');        }        int tot=d[n];        if(tot==0){               return 1ll*(n-1)*(n-2)/2%mod;        }        if(tot%3)return 0;        int l=1;        while(d[l]!=tot/3)l++;        int r=n;        while(d[n]-d[r-1]!=tot/3)r--;        int cntl=0,cntr=0;        for(int i=l+1;i<=n;i++){               if(s[i]=='0')cntl++;            else break;        }        for(int i=r-1;i>=1;i--){               if(s[i]=='0')cntr++;            else break;        }        return 1ll*(cntl+1)*(cntr+1)%mod;    }};

转载地址:http://igkv.baihongyu.com/

你可能感兴趣的文章
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>
No static resource favicon.ico.
查看>>
no such file or directory AndroidManifest.xml
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>