One deque solution java


  • 0
    G
    class Solution {
        public static int calculate(String s) {
            int len = s.length();
            Deque<Integer> sk = new ArrayDeque<>();
            
            for(int i=0; i<len; ){
                int j=i;
                if(s.charAt(j)==' '){
                	i++;
                	continue;
                }
                if(Character.isDigit(s.charAt(j))){
                    while(j<len && Character.isDigit(s.charAt(j))){
                        j++;
                    }
                
                    String curs = s.substring(i, j);//System.out.println(curs);
                    int curnum = Integer.valueOf(curs);
                    
                    if(!sk.isEmpty() && sk.peekLast()==(int)'*'){//System.out.println("aaaa");
                    	sk.pollLast();
                        int pre = sk.pollLast();
                        int newnum = pre*curnum;
                        sk.addLast(newnum);
                    }else if(!sk.isEmpty() && sk.peekLast()==(int)'/'){
                    	sk.pollLast();
                        int pre = sk.pollLast();
                        int newnum = pre/curnum;
                        sk.addLast(newnum);
                    }else{
                    	sk.addLast(curnum);
                    }
                    
                    i=j;
                }else{
                    sk.addLast((int)s.charAt(j));
                    i++;               
                }  
            }
            System.out.println(sk);
            
            while(sk.size()!=1){
                int first = sk.poll();//System.out.println(first);
                int c = sk.poll();//System.out.println(c);
                int second = sk.poll();//System.out.println(second);
                if(c==(int)'+'){
                    int newnum = first+second;
                    sk.addFirst(newnum);;
                }else{
                    int newnum = first-second;
                    sk.addFirst(newnum);
                }
            }    
            return sk.peek();
        }
    }
    

Log in to reply
 

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