Skip to content

Commit c3ef0ff

Browse files
authored
Merge pull request #3239 from giggling-ginger/ginger
1397 solution
2 parents 57ea8c1 + c2f6085 commit c3ef0ff

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

Diff for: python/0338-counting-bits.py

+14
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,17 @@ def countBits(self, n: int) -> List[int]:
88
offset = i
99
dp[i] = 1 + dp[i - offset]
1010
return dp
11+
12+
# Another dp solution
13+
class Solution2:
14+
def countBits(self, n: int) -> List[int]:
15+
res = [0] * (n + 1)
16+
for i in range(1, n + 1):
17+
if i % 2 == 1:
18+
res[i] = res[i - 1] + 1
19+
else:
20+
res[i] = res[i // 2]
21+
return res
22+
# This solution is based on the division of odd and even numbers.
23+
# I think it's easier to understand.
24+
# This is my full solution, covering the details: https://leetcode.com/problems/counting-bits/solutions/4411054/odd-and-even-numbers-a-easier-to-understanding-way-of-dp/

Diff for: python/1397-find-all-good-strings-i.py

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Solution:
2+
def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:
3+
a = ord('a')
4+
z = ord('z')
5+
6+
arr_e = list(map(ord, evil))
7+
len_e = len(evil)
8+
next = [0] * len_e
9+
10+
for i in range(1, len_e):
11+
j = next[i - 1]
12+
while j > 0 and evil[i] != evil[j]:
13+
j = next[j - 1]
14+
if evil[i] == evil[j]:
15+
next[i] = j + 1
16+
17+
def good(s):
18+
arr = list(map(ord, s))
19+
len_a = len(arr)
20+
21+
@cache
22+
def f(i, skip, reach, e):
23+
if e == len_e:
24+
return 0
25+
if i == len_a:
26+
return 0 if skip else 1
27+
28+
limit = arr[i] if reach else z
29+
ans = 0
30+
31+
if skip:
32+
ans += f(i + 1, True, False, 0)
33+
34+
for c in range(a, limit + 1):
35+
ee = e
36+
while ee > 0 and arr_e[ee] != c:
37+
ee = next[ee - 1]
38+
39+
if arr_e[ee] == c:
40+
ee += 1
41+
42+
ans += f(i + 1, False, reach and c == limit, ee)
43+
44+
return ans % int(1e9 + 7)
45+
46+
return f(0, True, True, 0)
47+
48+
return (good(s2) - good(s1) + int(evil not in s1)) % int(1e9 + 7)

0 commit comments

Comments
 (0)