[力扣] 算法 224 (C#)

224. 基本计算器

public class Solution
{
    public int Calculate(string s) => Bar(Foo(s));

    List<IConvertible> Foo(string s)
    {
        var stack = new Stack<char>(s.Length);// ( + - only
        var ret = new List<IConvertible>(s.Length);
        for (var i = 0; i < s.Length; i++)
        {
            var ch = s[i];
            switch (ch)
            {
                case '(':
                    stack.Push('(');
                    break;
                case ')':
                    char top;
                    while ((top = stack.Pop()) != '(')
                        ret.Add(top);
                    break;
                case '+':
                case '-':
                    while (stack.Count > 0 && stack.Peek() != '(')
                        ret.Add(stack.Pop());
                    stack.Push(ch);
                    break;
                case ' ':
                    break;
                default:// 0 ~ 9
                    long num = ch - '0';
                    for (; i + 1 < s.Length && s[i + 1] >= '0' && s[i + 1] <= '9'; i++)
                    {
                        num *= 10;
                        num += s[i + 1] - '0';
                    }
                    ret.Add(num);
                    break;
            }
        }
        while (stack.Count > 0)
            ret.Add(stack.Pop());
        return ret;
    }

    int Bar(List<IConvertible> foo)
    {
        var stack = new Stack<long>();
        foreach (var f in foo)
        {
            switch (f)
            {
                case '+':
                    stack.Push(stack.Pop() + stack.Pop());
                    break;
                case '-':
                    if (stack.Count > 1)
                        stack.Push(-(stack.Pop() - stack.Pop()));
                    else
                        stack.Push(-stack.Pop());
                    break;
                default:// long
                    stack.Push((long)f);
                    break;
            }
        }
        return (int)stack.Peek();
    }
}

参考资料

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注