leetcode 1513 仅含一的字串数
题目描述
给你一个二进制字符串 s(仅由 ‘0’ 和 ‘1’ 组成的字符串)。
返回所有字符都为 1 的子字符串的数目。
由于答案可能很大,请你将它对 10^9 + 7 取模后返回。
解答
这题没什么技术难度,难度主要体现在数据类型上
在使用java解题使用Biginteger的过程中我出现了点麻烦
从头到尾都因为一些Biginteger在很大数的计算上和我预期有些偏差导致始终过不了
java代码如下:
(java代码结果有问题之后训练完Biginteger类后可能会做一次修改)
/*
给定一个二进制字符串,确定其仅含1的字符串数目
最后对10^9+7取模
直观思路:
使用一个函数来确定子字符串长度对应的子字符串数目
每次碰见1之后一直向后判断一直到0
判断该全为1的字符串长度
最后使用sum把和相加
字符串遍历完成后对10^9+7取模即可
净搞些阴间东西
数据类型过不了
made我服了
*/
import java.math.BigInteger;
class Solution {
public static int numSub(String s) {
BigInteger sum = new BigInteger("0");
BigInteger count = new BigInteger("0");
while(count.intValue() < s.length()){
if(s.charAt(count.intValue()) == '1'){
BigInteger temp = new BigInteger("1");//temp是该子字符串长度
if(count.intValue() + temp.intValue() < s.length())while(s.charAt(count.intValue() + temp.intValue()) == '1'){
temp = temp.add(new BigInteger("1"));
if(count.intValue() + temp.intValue() == s.length())break;
}
count = count.add(temp.subtract(new BigInteger("1")));//因为count出了if还需要++
BigInteger _sum = new BigInteger("" + temp);
sum = sum.add(_sum.multiply(_sum.add(new BigInteger("1"))).divide(new BigInteger("2")));
}
count = count.add(new BigInteger("1"));
}
sum = sum.remainder(new BigInteger("100000007"));
return sum.intValue();
}
public static void main(String[] args) {
String s = new String("0110111");
/*Scanner x = new Scanner(System.in);
s = x.nextLine();
x.close();*/
System.out.println(numSub(s));
}
}
后来改用c++后
直接采用long long 数据类型,发现问题很快就解决了
十分顺利
/*
给定一个二进制字符串,确定其仅含1的字符串数目
最后对10^9+7取模
直观思路:
使用一个函数来确定子字符串长度对应的子字符串数目
每次碰见1之后一直向后判断一直到0
判断该全为1的字符串长度
最后使用sum把和相加
字符串遍历完成后对10^9+7取模即可
净搞些阴间东西
数据类型过不了
made我服了
*/
#include<iostream>
#include<string.h>
using namespace std;
class Solution {
public:
static int numSub(string s) {
long long sum = 0;
int count = 0;
while (count < s.length()) {
if (s.at(count) == '1') {
int temp = 1;//temp是该子字符串长度
if (count + temp < s.length())while (s.at(count + temp) == '1') {
temp++;
if (count + temp == s.length())break;
}
count += temp - 1;//因为count出了if还需要++
sum += (long long)temp * (temp + 1) / 2;
}
count++;
}
sum = sum % ((int)1e9 + 7);
return sum;
}
};
int main() {
string s = "0110111";
Solution x;
cout << x.numSub(s);
return 0;
}
时间击败87%
之后可能还需要对java的Biginteger类做一次系统的训练,但这题巨长无比输都输不进去的字符串也给了我很深的印象,我下次随机题的时候必会先看这题的评价,草了,今晚真的是啥也没学到。