精華區beta Marginalman 關於我們 聯絡資訊
https://leetcode.com/problems/minimum-number-of-changes-to-make-binary-string-beautiful 2914. Minimum Number of Changes to Make Binary String Beautiful 給一個長度為偶數、索引起始為0的二進位字串 s beautiful 的條件是 每個子字串的長度都是偶數 每個子字串只包含1或只包含0 可以將s中的任何字元改成0或1 回傳變成beautiful的最少更改次數 Example 1: Input: s = "1001" Output: 2 Explanation: s[1] 換成 1 s[3] 換成0 變成 "11 | 00" Example 2: Input: s = "10" Output: 1 Example 3: Input: s = "0000" Output: 0 Constraints: 2 <= s.length <= 10^5 s 長度為偶數 s[i] 只有 '0' 或 '1' 思路: 字元兩兩相比 不同就+1 range用2可以加快判斷速度 Python Code: class Solution: def minChanges(self, s: str) -> int: if len(set(s)) == 1: return 0 cnt = 0 for i in range(0, len(s), 2): if s[i] != s[i+1]: cnt += 1 return cnt 或是直接一行 return sum(s[i] != s[i+1] for i in range(0, len(s), 2)) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.45.55.73 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1730806404.A.FC7.html
JerryChungYC: 因為子字串要偶數 所以兩兩一組最快 11/05 19:35
dont: 大師 11/05 19:41