Algorithm/문제풀이
[Leetcode] Leetcode 696 - count binary substring - python3
Razelo
2022. 5. 27. 16:33
최근에 리트코드를 풀고 있는데 696 문제에서 막혀서 수십분 정도를 낭비했다. 이후에 discuss에 있는 솔루션 중 하나를 참고했는데 코드가 너무 이뻐서 올려둔다.
class Solution(object):
def countBinarySubstrings(self, s):
"""
:type s: str
:rtype: int
"""
#Using the map function to find the combined length of 0 and 1 that are cut apart
L = list(map(len, s.replace('01', '0 1').replace('10', '1 0').split('')))
#Because it is limited that only 0 and 1 can be next to each other, only adjacent ones can team up, using the zip function
res = sum(min(a,b) for a,b in zip(L, L[1:]))
return res
읽어보면 상당히 간단한 코드이다. 그런데 이렇게 생각한게 신기하기도 하고 풀어낸 방법 자체가 꽤나 우아한것 같다. 참고로 길이가 다른 두 List를 대상으로 ZIP 을 사용하면 에러가 날 것이라는 내 예상과는 다르게 작은 쪽 List 쪽으로 맞춰서 출력된다. 즉 더 긴 List에서 남은 부분은 그냥 짤린다.
이 점이 신기하기도 하고 map 에 len 을 적용한 것도 처음봤다.
해당 블로그를 참고했다.
감사합니다.
https://blog.karatos.in/a?ID=00800-671c42ed-d4e1-442f-8fac-ffe5c9d3ec43
leetcode 696. Counting binary substrings (python) - Karatos
blog.karatos.in
반응형