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 。