herrDeng網內搜尋

自訂搜尋

Ads

2024年4月6日 星期六

python C++字串deque解Leetcode 1249 Minimum Remove to Make Valid Parentheses


python C++字串deque解Leetcode 1249  Minimum Remove to Make Valid Parentheses
連續幾天都是含括號的字串問題Leetcode 1249. Minimum Remove to Make Valid Parentheses,都提示用stack其實不用,走訪兩次就好,一次去掉多的 ')' ,第二反向去掉多的 '(' ;選用適當的容器,字串、deque就得解了,最快的C++解請進
---
Leetcode 1249. Minimum Remove to Make Valid Parentheses has been a problem with strings containing parentheses for several days in a row. It all prompts that stack is not necessary. Just visit twice. One time to remove too many ')'s, and the second time in reverse to remove too many '('s ;Choose an appropriate container, and the string and deque will have to be solved.
  1. #pragma GCC optimize("O3", "unroll-loops")
  2. class Solution {
  3. public:
  4. string minRemoveToMakeValid(string& s) {
  5. int p=0, n=s.size();
  6. for(int i=n-1; i>=0; i--){
  7. char& c=s[i];
  8. p+=(c=='(')-(c==')');
  9. if (p>0) c='@', p=0;
  10. }
  11. int sz=n;
  12. p=0;
  13. for(int i=0, j=0; i=0) s[j++]=c;
  14. else sz--, p=0;
  15. }
  16. s.resize(sz, '\0');
  17. return s;
  18. }
  19. };
  20. auto init = []()
  21. {
  22. ios::sync_with_stdio(0);
  23. cin.tie(0);
  24. cout.tie(0);
  25. return 'c';
  26. }();
  27.  

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章