Re: [閒聊] 每日leetcode

看板Marginalman作者 (是oin的說)時間1年前 (2024/10/08 16:08), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串964/1548 (看更多)
1963. 題目: 有一群[ ] 你可以交換他們的位子 最少幾次交換可以讓他左右括號都匹配 思路: 用two pointer在兩邊紀錄左右括號的數量 有缺的話就去其他地方拿並記錄次數 ```cpp class Solution { public: int minSwaps(string s) { int res = 0; int n = s.size(); int l = 0 ; int r = n-1; int lcnt = 0; int rcnt = 0; while(l<r) { if(s[l] == '[')lcnt ++; else lcnt --; if(s[r] == ']')rcnt ++; else rcnt --; while(lcnt < 0 || rcnt < 0) { res ++; lcnt +=2; rcnt +=2; } l++; r--; } return res; } }; // ][]][[ // [ ] // []][ // ]]][[[ ``` -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 101.12.26.137 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1728374922.A.4A0.html
文章代碼(AID): #1d1EYAIW (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1d1EYAIW (Marginalman)