Not concise at all c# solution


  • 0
    C
    public IList<int> DiffWaysToCompute(string input)
    {
        string[] parts = this.Split(input);
        var result = new List<int>();
    
        result.AddRange(this.Compute(parts, 0, parts.Length - 1));
    
        return result;
    }
    
    private IList<int> Compute(string[] parts, int start, int end)
    {
        if (start == end)
            return new[] { int.Parse(parts[start]) };
    
        var result = new List<int>();
    
        for (int i = start + 1; i <= end - 1; i += 2)
        {
            var leftResults = this.Compute(parts, start, i - 1);
            var rightResults = this.Compute(parts, i + 1, end);
            string operartor = parts[i];
    
            foreach (int left in leftResults)
            {
                foreach (int right in rightResults)
                {
                    result.Add(
                        this.Calculate(
                        left,
                        right,
                        operartor));
                }
            }
        }
    
        return result;
    }
    
    private string[] Split(string input)
    {
        var sb = new StringBuilder();
        var result = new List<string>();
    
        for (int i = 0; i < input.Length; ++i)
        {
            if (char.IsDigit(input[i]))
            {
                sb.Append(input[i]);
            }
            else
            {
                result.Add(sb.ToString());
                result.Add(input[i].ToString());
                sb.Clear();
            }
        }
    
        result.Add(sb.ToString());
    
        return result.ToArray();
    }
    
    private int Calculate(int left, int right, string @operator)
    {
        switch (@operator)
        {
            case "+": return left + right;
            case "*": return left * right;
            case "-": return left - right;
        }
    
        throw new ArgumentException("bad operator");
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.