Baseball Game


  • 0

    Click here to see the full article post


  • 1

    Why don't you keep track of sum inside the same for loop instead of having a separate loop afterwards?
    public int CalPoints(string[] ops) //with Stack
    {
    Stack<int> stack = new Stack<int>();
    int sum = 0;
    for (int i = 0; i < ops.Length; i++)
    {
    string s = ops[i];
    switch (s)
    {
    case "+":
    int temp = stack.Pop();
    int n = stack.Peek() + temp;
    sum += n;
    stack.Push(temp);
    stack.Push(n);
    break;
    case "D":
    int m = stack.Peek()* 2;
    sum += m;
    stack.Push(m);
    break;
    case "C":
    sum -= stack.Pop();
    break;
    default: //if integer
    stack.Push(int.Parse(s));
    sum += int.Parse(s);
    break;
    }
    }
    return sum;
    }


  • 0
    W

    I wrote a solution using a normal array as a stack.
    Taking a sum at the end is essentially fewer operations than keeping track of the sum during the for loop.

    My initial submittion with summation at end took 7ms
    My second submission with summation in for loop took 9ms.


  • 0

    @yashar My reason wasn't related to waykole's "fewer operations" motivation, I just thought it was a simpler presentation for people trying to read the article and understand.


Log in to reply
 

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