leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

1541.cpp (687B)


      1 class Solution {
      2   public:
      3     int minInsertions(string s) const {
      4         const int n = size(s);
      5         int res = 0, cnt = 0;
      6 
      7         s.push_back(' ');
      8         for (int i = 0; i < n; i++) {
      9             if (s[i] == '(')
     10                 cnt++;
     11             else {
     12                 if (cnt) {
     13                     if (s[i + 1] == ')')
     14                         i++;
     15                     else
     16                         res++;
     17                     cnt--;
     18                 } else {
     19                     if (s[i + 1] == ')')
     20                         res++, i++;
     21                     else
     22                         res += 2;
     23                 }
     24             }
     25         }
     26 
     27         return res + cnt * 2;
     28     }
     29 };