1 Star 0 Fork 8

gohin / leetcode

forked from 程序员二师兄 / leetcode 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
LeetCode_682.java 1.44 KB
一键复制 编辑 原始数据 按行查看 历史
程序员二师兄 提交于 2019-09-29 19:36 . add stack 3 problems
import java.util.Stack;
/**
* @创建人 luoxiang
* @创建时间 2019/9/27 16:11
* @描述 682. 棒球比赛 https://leetcode-cn.com/problems/baseball-game/
*/
public class LeetCode_682 {
public static void main(String[] args) {
System.out.println(new LeetCode_682().calPoints(new String[]{"5", "2", "C", "D", "+"}));
System.out.println(new LeetCode_682().calPoints(new String[]{"5", "-2", "4", "C", "D", "9", "+", "+"}));
}
/** Method 1
* Created by LuoXiang on 2019/09/27 16:28
* Desc: 思路 —— 利用栈来保存每轮的操作。
* 复杂度: 时间复杂度:O(n) ; 空间复杂度:O(n)
**/
public int calPoints(String[] ops) {
Stack<Integer> stack = new Stack<>();
for (String op : ops) {
switch (op) {
case "+":
Integer last = stack.pop();
Integer lastTwo = stack.peek();
stack.push(last);
stack.push(last + lastTwo);
break;
case "D":
stack.push(stack.peek() * 2);
break;
case "C":
stack.pop();
break;
default:
stack.push(Integer.valueOf(op));
}
}
int sum = 0;
while (!stack.empty()) {
sum += stack.pop();
}
return sum;
}
}
1
https://gitee.com/gohin/leetcode.git
git@gitee.com:gohin/leetcode.git
gohin
leetcode
leetcode
master

搜索帮助