From d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa Mon Sep 17 00:00:00 2001 From: jack <0x6A73@pm.me> Date: Fri, 14 Jun 2024 13:13:15 -0600 Subject: initial --- min_change_alt_binary_str.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 min_change_alt_binary_str.py (limited to 'min_change_alt_binary_str.py') diff --git a/min_change_alt_binary_str.py b/min_change_alt_binary_str.py new file mode 100644 index 0000000..aaf2e05 --- /dev/null +++ b/min_change_alt_binary_str.py @@ -0,0 +1,39 @@ +# 1758. Minimum Changes To Make Alternating Binary String + +""" +given a string 's' consisting only of the characters '0' and '1', in one +operation, you can change any '0' to '1' or vice versa. the string is called +alternating if no two adjacent characters are equal. for example the string +"010" is alternating, while the string "0100" is not. return the minimum +number of operations needed to make 's' alternating. +""" + + +class Solution(object): + def count(self, s, pre): + cnt = 0 + for i in range(1, len(s)): + curr = s[i] + if curr == pre: + cnt += 1 + pre = "0" if pre == "1" else "1" + else: + pre = curr + return cnt + + def minOperations(self, s): + """ + :type s: str + :rtype: int + """ + c0 = s[0] + cnt1 = self.count(s, c0) + cnt2 = self.count(s, "0" if c0 == "1" else "1") + 1 + return min(cnt1, cnt2) + + +if __name__ == "__main__": + obj = Solution() + print(obj.minOperations("0100")) # expect: 1 + print(obj.minOperations("10")) # expect: 0 + print(obj.minOperations("1111")) # expect: 2 -- cgit v1.2.3