682. Baseball Game
MA:
class Solution {
public int calPoints(String[] ops) {
Integer score=0;
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<ops.length;i++){
switch(ops[i]){
case "D":
stack.push(2*stack.peek());
break;
case "+":
int temp=stack.pop();
int insertBuffer=temp+stack.peek();
stack.push(temp);
stack.push(insertBuffer);
break;
case "C":
stack.pop();
break;
default:
stack.push(Integer.parseInt(ops[i]));
break;
}
}
while(stack.empty()!=true){
score+=stack.pop();
}
return score;
}
}
OA:
class Solution { public int calPoints(String[] ops) { int sum = 0; int[] valid = new int[ops.length]; int v = -1; for(int i = 0; i < ops.length; i++){ if(ops[i].equals("C")){ sum -= valid[v]; v--; } else if(ops[i].equals("D")){ int d = valid[v] + valid[v]; v++; valid[v] = d; sum += d; } else if(ops[i].equals("+")){ int p = valid[v] + valid[v - 1]; v++; valid[v] = p; sum += p; } else { int val = Integer.parseInt(ops[i]); v++; valid[v] = val; sum += val; } } return sum; } }
用数组做的
class Solution {
public int calPoints(String[] ops) {
Integer score=0;
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<ops.length;i++){
switch(ops[i]){
case "D":
stack.push(2*stack.peek());
break;
case "+":
int temp=stack.pop();
int insertBuffer=temp+stack.peek();
stack.push(temp);
stack.push(insertBuffer);
break;
case "C":
stack.pop();
break;
default:
stack.push(Integer.parseInt(ops[i]));
break;
}
}
while(stack.empty()!=true){
score+=stack.pop();
}
return score;
}
}
OA:
class Solution { public int calPoints(String[] ops) { int sum = 0; int[] valid = new int[ops.length]; int v = -1; for(int i = 0; i < ops.length; i++){ if(ops[i].equals("C")){ sum -= valid[v]; v--; } else if(ops[i].equals("D")){ int d = valid[v] + valid[v]; v++; valid[v] = d; sum += d; } else if(ops[i].equals("+")){ int p = valid[v] + valid[v - 1]; v++; valid[v] = p; sum += p; } else { int val = Integer.parseInt(ops[i]); v++; valid[v] = val; sum += val; } } return sum; } }
用数组做的
评论
发表评论