-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1513-NumberOfSubstringsWithOnlyOnes.go
More file actions
100 lines (89 loc) · 2.58 KB
/
1513-NumberOfSubstringsWithOnlyOnes.go
File metadata and controls
100 lines (89 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
// 1513. Number of Substrings With Only 1s
// Given a binary string s, return the number of substrings with all characters 1's.
// Since the answer may be too large, return it modulo 10^9 + 7.
// Example 1:
// Input: s = "0110111"
// Output: 9
// Explanation: There are 9 substring in total with only 1's characters.
// "1" -> 5 times.
// "11" -> 3 times.
// "111" -> 1 time.
// Example 2:
// Input: s = "101"
// Output: 2
// Explanation: Substring "1" is shown 2 times in s.
// Example 3:
// Input: s = "111111"
// Output: 21
// Explanation: Each substring contains only 1's characters.
// Constraints:
// 1 <= s.length <= 10^5
// s[i] is either '0' or '1'.
import "fmt"
func numSub(s string) int {
res, n, mod := 0, 0, 1_000_000_007
for _, v := range s {
if v == '1' {
n += 1
} else {
n = 0
}
res = (res + n) % mod
}
return res
}
func numSub1(s string) int {
res, count, n := int64(0), 0, len(s)
prefixSum := make([]int64,n + 1)
for i := 1 ; i < n + 1; i++ {
prefixSum[i] = prefixSum[i-1] + int64(i)
}
for _, v := range s {
if v == '1' { // 1
count += 1
} else { // 0
res = res + prefixSum[count]
count = 0
}
}
if count != 0 {
res = res + prefixSum[count]
}
return int(res % 1_000_000_007)
}
func main() {
// Example 1:
// Input: s = "0110111"
// Output: 9
// Explanation: There are 9 substring in total with only 1's characters.
// "1" -> 5 times.
// "11" -> 3 times.
// "111" -> 1 time.
fmt.Println(numSub("0110111")) // 9
// Example 2:
// Input: s = "101"
// Output: 2
// Explanation: Substring "1" is shown 2 times in s.
fmt.Println(numSub("101")) // 2
// Example 3:
// Input: s = "111111"
// Output: 21
// Explanation: Each substring contains only 1's characters.
fmt.Println(numSub("111111")) // 21
fmt.Println(numSub("1111111111")) // 55
fmt.Println(numSub("0000000000")) // 0
fmt.Println(numSub("1111100000")) // 15
fmt.Println(numSub("0000011111")) // 15
fmt.Println(numSub("0101010101")) // 5
fmt.Println(numSub("1010101010")) // 5
fmt.Println(numSub1("0110111")) // 9
fmt.Println(numSub1("101")) // 2
fmt.Println(numSub1("111111")) // 21
fmt.Println(numSub1("1111111111")) // 55
fmt.Println(numSub1("0000000000")) // 0
fmt.Println(numSub1("1111100000")) // 15
fmt.Println(numSub1("0000011111")) // 15
fmt.Println(numSub1("0101010101")) // 5
fmt.Println(numSub1("1010101010")) // 5
}