LeetCode-682 Baseball Game Solution (with Java)

1. Description:

 

 Notes:

2. Examples:

3.Solutions:

 1 /**
 2  * Created by sheepcore on 2018-12-24
 3  */
 4 class Solution {
 5     public int calPoints(String[] ops) {
 6         Stack<Integer> numStack = new Stack<>();
 7         String op;
 8         for(int i = 0; i < ops.length; i++){
 9             op = ops[i];
10             if(op.matches("-?\\d+"))
11                 numStack.push(Integer.parseInt(op));
12 
13             //cut off the point in last round
14             else if(op.equals("C") || op.equals("c"))
15                 numStack.pop();
16             //double the point in last round
17             else if(op.equals("D") || op.equals("d")){
18                 int top = numStack.peek();
19                 numStack.push((top << 1));
20             }
21             //add the last two round numbers
22             else if(op.equals("+")){
23                 int top = numStack.pop();
24                 int stop = numStack.peek();
25                 numStack.push(top);
26                 numStack.push(top + stop);
27             }
28             //go cycling if not reach the end
29             else
30                 continue;
31         }
32         int totalPoints = 0;
33         Iterator<Integer> iterator = numStack.iterator();
34         while(iterator.hasNext()){
35             totalPoints += iterator.next();
36         }
37         return totalPoints;
38     }
39 }

 

posted @ 2020-03-02 16:51  SheepCore  阅读(151)  评论(0)    收藏  举报