Tuesday, February 23, 2021

Leetcode Everyday: 1021. Remove Outermost Parentheses. Easy

public class Solution {
    public string RemoveOuterParentheses(string s) {
        var sb = new StringBuilder();        
    
        var opList = new Dictionary<char, int> {
            ['('] = 1,
            [')'] = -1
        };
        
        int depth = 0;
        foreach (var c in s) {
            var op = opList[c];
            depth += op;
            if (op == 1 && depth > 1 || op == -1 && depth > 0) {
                sb.Append(c);
            }
        }
        
        return sb.ToString();
    }
}
Compact condition:
public class Solution {
    public string RemoveOuterParentheses(string s) {
        var sb = new StringBuilder();
         
     
        // KeyValue<op, depth>
        // op = 1 = increment
        // op = -1 = decrement
        var opList = new Dictionary<char, KeyValuePair<int, int>> {
            ['('] = new KeyValuePair<int, int>(1, 1),
            [')'] = new KeyValuePair<int, int>(-1, 0)
        };
         
         
        int depth = 0;
        foreach (var c in s) {
            var (op, opDepth) = opList[c];
            depth += op;
                  
            if (depth > opDepth) {
                sb.Append(c);
            }
        }
         
        return sb.ToString();
    }
}
Source: https://leetcode.com/problems/remove-outermost-parentheses/

No comments:

Post a Comment