Created
September 24, 2017 02:06
-
-
Save cixuuz/a6340422b901f25c8a1d76bd628d414f to your computer and use it in GitHub Desktop.
[682. Baseball Game] #leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public int calPoints(String[] ops) { | |
int sum = 0; | |
if (ops.length == 0 || ops == null) return sum; | |
Deque<Integer> stack = new LinkedList<Integer>(); | |
for (int i = 0 ; i < ops.length ; i++) { | |
if (ops[i].matches("-?\\d+(\\.\\d+)?")) { | |
int val = Integer.valueOf(ops[i]); | |
stack.addLast(val); | |
sum += val; | |
} else if (ops[i].equals("+")) { | |
int lastOne = 0, lastTwo = 0; | |
if (stack.size() != 0) { | |
lastOne = stack.removeLast(); | |
if (stack.size() != 0) { | |
lastTwo = stack.peekLast(); | |
} | |
stack.addLast(lastOne); | |
} | |
stack.addLast(lastOne + lastTwo); | |
sum += lastOne + lastTwo; | |
} else if (ops[i].equals("D")) { | |
if (stack.size() != 0) { | |
sum += stack.peekLast() * 2; | |
stack.addLast(stack.peekLast() * 2); | |
} | |
} else { | |
if (stack.size() != 0) { | |
sum -= stack.removeLast(); | |
} | |
} | |
} | |
return sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment