Description
描述的篇幅太大了,戳→https://leetcode.com/problems/baseball-game/description/
我的解决方法
import java.util.*;
class Solution {
public int calPoints(String[] ops) {
int sum = 0;
int[] scores = new int[ops.length];
for(int i=0; i<ops.length; i++){
if( ops[i].equals("C") ){
sum = sum - LastValid(scores,i);
//remove last valid score
for(int j=i-1; j>=0; j--){
if(scores[j]!=0){
scores[j] = 0;
break;
}
}
scores[i] = 0;
}
else if( ops[i].equals("D")){
scores[i] = 2*LastValid(scores,i);
sum += scores[i];
}
else if( ops[i].equals("+")){
scores[i] = Last2Valid(scores,i);
sum += scores[i];
}
else{
if(ops[i].charAt(0)=='-'){
scores[i] = - Integer.valueOf(ops[i].substring(1,ops[i].length()));
}
else{
scores[i] = Integer.valueOf(ops[i]);
}
sum += scores[i];
}
}
return sum;
}
public int LastValid(int[] scores,int a){
int res = 0;
for(int i=a-1; i>=0; i--){
if(scores[i]!=0){
res = scores[i];
break;
}
}
return res;
}
public int Last2Valid(int[] scores, int a){
int res = 0;
for(int i=a-1; i>=0; i--){
if(scores[i]!=0){
res = scores[i]+LastValid(scores,i);
break;
}
}
return res;
}
}
最近在学java,解决这个问题用的仍然是最基础的东西。虽然AC但是效率不高,Runtime为10 ms。我想看一下和Solution的Runtime对比结果,把代码粘过来发现不能跑,简单修改之后AC了。它的Runtime是10ms,后来跑了一次是15ms。下面就从Solution中学习一下Stack。
修改后的Solution:
import java.util.*;
class Solution {
public int calPoints(String[] ops) {
Stack<Integer> stack = new Stack();
for(String op : ops) {
if (op.equals("+")) {
int top = stack.pop();
int new1 = top + stack.peek();
stack.push(top);
stack.push(new1);
} else if (op.equals("C")) {
stack.pop();
} else if (op.equals("D")) {
stack.push(2 * stack.peek());
} else {
stack.push(Integer.valueOf(op));
}
}
int ans = 0;
for(int score : stack) ans += score;
return ans;
}
}
好,开始看Stack
E push(E item)
把item压入栈顶
E pop()
移除栈顶的对象,并作为此函数的值返回该对象。
E peek()
查看堆栈顶部的对象,但不从堆栈中移除它。
boolean empty()
判断栈是否为空
int search(Object o)
返回对象在堆栈中的位置,以 1 为基数,不是 0 。