Re: [閒聊] 每日leetcode
看板Marginalman作者sustainer123 (溫水佳樹的兄長大人)時間1年前 (2024/10/08 09:40)推噓0(0推 0噓 0→)留言0則, 0人參與討論串962/1548 (看更多)
※ 引述《dont (dont)》之銘言:
: 1963. Minimum Number of Swaps to Make the String Balanced
: ## 思路
: 計算不match的pair數量, swap次數=(res+1) // 2
: ][ -- 1 ([ ])
: ]][[ -- 1 ([][])
: ]]][[[ -- 2 ([ [][] ])
: ]]]][[[[ -- 2 ([][][][])
: ]]]]][[[[[ -- 3 ([ [][][][] ])
: ## Code
: ```python
: class Solution:
: def minSwaps(self, s: str) -> int:
: res = left = 0
: for ch in s:
: if ch == '[':
: left += 1
: elif left == 0:
: res += 1
: else:
: left -= 1
: return (res + 1) // 2
: ```
思路:
照提示寫
Python Code:
class Solution:
def minSwaps(self, s: str) -> int:
if "[" not in s and "]" not in s:
return 0
balance = 0
result = 0
for i, b in enumerate(s):
if b == "[":
balance += 1
elif b == "]":
balance -= 1
if balance < 0:
balance += 2
result += 1
return result
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.194.160.111 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1728351630.A.18A.html
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 962 之 1548 篇):