Re: [閒聊] 每日leetcode
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
討論串 (同標題文章)
完整討論串 (本文為第 964 之 1548 篇):