Re: [閒聊] 每日leetcode

看板Marginalman作者 (JerryChung)時間1年前 (2024/11/05 19:33), 編輯推噓1(101)
留言2則, 2人參與, 1年前最新討論串1079/1548 (看更多)
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

11/05 19:35, 1年前 , 1F
因為子字串要偶數 所以兩兩一組最快
11/05 19:35, 1F

11/05 19:41, 1年前 , 2F
大師
11/05 19:41, 2F
文章代碼(AID): #1dAWA4_7 (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1dAWA4_7 (Marginalman)