Baseball, Linked List O(n) space complexity and time complexity


  • 0
    A

    first element of linked list contains the result of latest operation.

    import java.io.*;
    import java.util.*;11
    class Solution {
        public int calPoints(String[] ops) {
            LinkedList<Integer> res=new LinkedList();
        	res.add(0);
        	for (String s:ops){
        		if(!s.equals("D") && !s.equals("C") && !s.equals("+")){
        			int a=Integer.valueOf(s);
        			res.addFirst(a);
        		}else if(s.equals("D")){
        			res.addFirst(2*res.getFirst());
        		}else if(s.equals("C")){
        			res.removeFirst();
        		}else if(s.equals("+")){
        			res.addFirst(res.get(0)+res.get(1));
        		}
        	}
        	int sum=0;
        	for (int a:res){
        		sum+=a;
        	}
        	return sum;
        }
    
        public static void main(String arg[]){
        	System.out.println("\n"+new Solution().calPoints(new String[]{"5","-2","4","C","D","9","+","+"}));
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.