-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcount_binary_substrings.py
More file actions
42 lines (34 loc) ยท 1.95 KB
/
count_binary_substrings.py
File metadata and controls
42 lines (34 loc) ยท 1.95 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
# 696. Count Binary Substrings
# https://leetcode.com/problems/count-binary-substrings/
class Solution:
# 0๊ณผ 1๋ก ์ด๋ฃจ์ด์ง ๋ฌธ์์ด์ด ๋ค์ด์จ๋ค. ์ด ๋ 0๊ณผ 1์ด ๊ฐ์ ์นด์ดํธ๋ก ๋ฑ์ฅํ๋ ๋ชจ๋ ๋ถ๋ถ ๋ฌธ์์ด์ ๊ฐ์๋ฅผ ๋ฆฌํดํ๋ ๋ฌธ์ ๋ค.
def countBinarySubstrings(self, s: str) -> int:
# ๋ค์ด์ค๋ 0๊ณผ 1๋ก ์ด๋ฃจ์ด์ง ๋ฌธ์์ด์ ๊ทธ๋ฃนํํ ์นด์ดํธ๋ฅผ ์ฐ์ ๊ตฌํ๋ค.
# ์๋ฅผ ๋ค๋ฉด "00110011" ์ [2, 2, 2, 2] ๊ฐ ๋๋ค. ์ด๋ฅผ group ์ด๋ผ๊ณ ์ฐ์ ํ๋ค.
# "00110011" ์ "0011", "01", "1100", "10", "01", "0011" ์ด 6๊ฐ์ ๊ฒฝ์ฐ๊ฐ ๋์จ๋ค.
# ์ฒซ๋ฒ์งธ "0011" ์ group[0]๊ณผ group[1] ์ ๊ฒฐ๊ณผ ๊ฐ์ด๋ค.
# ๋๋ฒ์งธ "01" ์ "0011" ์ ๋ถ๋ถ ๋ฌธ์์ด์ด๋ค.
# ์ฌ๊ธฐ๊น์ง์ ๊ฒฐ๊ณผ ๊ฐ์ group[0] ๊ณผ group[1] ์ ์ต์๊ฐ 2์ ๊ฐ๋ค.
# ์ฆ min(group[i-1], group[i]) ์ ๋์ ํ๋ ๊ฒ์ด๋ค.
# ์ต์๊ฐ์ผ๋ก ํ๋ ์ด์ ๋ "100" ์ด๋ผ๋ [1, 2] ๋ผ๋ ๋ฆฌ์คํธ๊ฐ ๋ง๋ค์ด์ง๋ค๋ฉด ์ฌ๊ธฐ์ ์๊ธธ ์ ์๋ ๋ถ๋ถ ๋ฌธ์์ด์ "10" ์ด๋ฉฐ ํ๋ ๋ฐ์ ์๋ค.
# ์ฆ ๊ฐ์ ์ซ์๋ก ๊ทธ๋ฃนํ์ ํ๋๋ฐ ๋์ฌ ์ ์๋ ๊ฐ์ ๋ฌธ์์ด์ ์ต์๊ฐ์ผ ์ ๋ฐ์ ์๋ค๋ ๊ฑด๋ฐ
# (1์ด ํ๋๊ณ 0์ด ๋๊ฐ์ธ๋ฐ ์ฐ์์ ์ด์ด์ผ ํ๋ค๋ฉด ์ต์ ๊ฐ์ ๋ฐ๋ฅผ ์ ๋ฐ์ ์๊ฒ ์ง?) ๋ญ๊ฐ ์ค๋ช
์ ์ ๋ชป ํ์ด ์ฐ๊ฒ ๋ค.
group = [1]
pre = s[0]
pre_idx = 0
for i in range(1, len(s)):
if pre == s[i]:
group[pre_idx] += 1
else:
group.append(1)
pre_idx += 1
pre = s[i]
res = 0
for i in range(1, len(group)):
res += min(group[i - 1], group[i])
return res
if __name__ == '__main__':
sol = Solution()
assert sol.countBinarySubstrings("00110011") == 6
assert sol.countBinarySubstrings("10101") == 4
assert sol.countBinarySubstrings("1100") == 2