描述:给出一个只包含0或1的字符串str,请返回这个字符串中全为0的子字符串的个数1<=|str|<=30000样例1:输入:"00010011" 输出:9 解释: "0"子字符串有5个, "00"子字符串有3个, "000"子字符串有1个。 所以返回9样例2:输入: "010010" 输出: 5
解题思路1:
暴力数学法:
通过数学方法解决该问题字符串个数公式为(1+n)*n/2
解题代码
public static void main(String[] args) {//int [] A = new int[] {1,1,2};String str = "0001001";stringCount(str);}public static int stringCount(String str) {int m = 0;int n = 0;char[] cs = str.toCharArray();//返回字符数组for (char c : cs) {//遍历字符数组//System.out.println(c);if (c=='0') {//如果字符等于'0'n++;//那么n+1}else {//如果字符不等于'0'm+=(1+n)*n/2;//m等于1到n的和。。即m=1到n的和n=0;}}if (n!=0) {m+=(1+n)*n/2;}System.out.println(m);return m;}
