问题描述:
ou are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds’ scores.
At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the ith operation you must apply to the record and is one of the following:
An integer x - Record a new score of x.
“+” - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.
“D” - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.
“C” - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.
Return the sum of all the scores on the record.
棒球计分板:给定一个字符串类型的数组,如果字符串代表数字,则记录该分数;如果字符串为“+”,则记录前两个数字之和;若为“D”,则记录上一个数字的*2;若为“C”, 则抹去上一个记录。
思路:
形式新颖但思路很传统,就是逐一解析每一个位置,然后对应一个数组操作。
代码如下:
class Solution {
public int calPoints(String[] ops) {
List<Integer> myList = new ArrayList<>();
int listPointer = 0;
int sum = 0;
for (int i=0; i<ops.length; i++){
String thisSymbol = ops[i];
if((!thisSymbol.equals("+"))&&(!thisSymbol.equals("D"))&&(!thisSymbol.equals("C"))){
myList.add(Integer.parseInt(thisSymbol));
listPointer++;
}
else if (thisSymbol.equals("+")){
myList.add(myList.get(listPointer-2)+myList.get(listPointer-1));
listPointer++;
}
else if(thisSymbol.equals("D")){
myList.add(myList.get(listPointer-1)*2);
listPointer++;
}
else{
myList.remove(--listPointer);
}
}
for(int i=0; i<myList.size(); i++){
sum = sum+myList.get(i);
}
return sum;
}
}
老生常谈,加深印象:如果需要数组但未知数组大小,各异借助arraylist然后转换成数组
时间复杂度: O(n)