博客
关于我
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/

你可能感兴趣的文章
mysql命令
查看>>
mysql命令==_mysql命令
查看>>
mysql命令和mysql的配置文件
查看>>
watch
查看>>
MySQL命令行操作的相关语法
查看>>
MySQL命令行登陆,远程登陆MySQL
查看>>
mysql命令:set sql_log_bin=on/off
查看>>
mySQL和Hive的区别
查看>>
MySQL和Java数据类型对应
查看>>
mysql和oorcale日期区间查询【含左右区间问题】
查看>>
MYSQL和ORACLE的一些操作区别
查看>>
mysql和redis之间互相备份
查看>>
MySQL和SQL入门
查看>>
mysql在centos下用命令批量导入报错_Variable ‘character_set_client‘ can‘t be set to the value of ‘---linux工作笔记042
查看>>
Mysql在Linux运行时新增配置文件提示:World-wrirable config file ‘/etc/mysql/conf.d/my.cnf‘ is ignored 权限过高导致
查看>>
Mysql在Windows上离线安装与配置
查看>>
MySQL在渗透测试中的应用
查看>>
Mysql在离线安装时启动失败:mysql服务无法启动,服务没有报告任何错误
查看>>
Mysql在离线安装时提示:error: Found option without preceding group in config file
查看>>
MySQL基于SSL的主从复制
查看>>