字符串算式遞歸方法

package 遞歸方法;

import java.util.ArrayList;
import java.util.Stack;

import javax.jws.Oneway;

public class Main {
	static int getpi(ArrayList<Object> list,int start){
		Stack<Character> stack=new Stack<>();
		for(int i=start;i<list.size();++i){
			Object ob=list.get(i);
			if(ob instanceof Character){
				if((char)ob=='('){
					stack.push((Character) ob);
				}
				else if((char)ob==')'){
					stack.pop();
					if(stack.isEmpty()){
						return i;
					}
				}
			}
		}
		return -1;
	}
	static int dfs(ArrayList<Object> list,int start,int end){
		ArrayList<Object> l2=new ArrayList<>();
		for(int i=start;i<=end;){
			if(list.get(i) instanceof Integer){
				l2.add(list.get(i));
				i++;
			}
			else{
				if((char)list.get(i)!='('){
					l2.add(list.get(i));
					++i;
				}else{
					int rear=getpi(list, i);
					l2.add(dfs(list,i+1,rear-1));
					i=rear+1;
				}
			}
		}
		
		Stack<Object> stack=new Stack<>();
		for(int i=0;i<l2.size();++i){
			Object object=l2.get(i);
			if(object instanceof Integer){
				if(!stack.isEmpty()&&stack.peek() instanceof Character){
					char top=(char) stack.peek();
					if(top=='*'){
						stack.pop();
						Integer last=(Integer) stack.pop();
						stack.push(last*(Integer)object);
						
					}
					else if(top=='/'){
						stack.pop();
						Integer last=(Integer) stack.pop();
						stack.push(last/(Integer)object);
					}
					else{
						stack.push(object);
					}
				}
				else{
					stack.push(object);
				}
			}
			else{
				stack.push(object);
			}
		}
		Integer sum=(Integer) stack.get(0);
		for(int i=1;i<stack.size();++i){
			 if ( stack.get(i) instanceof Integer) {
				if(i-1>=0){
					if((char)stack.get(i-1)=='+'){
						sum=sum+(Integer)stack.get(i);
					}
					else{
						sum=sum-(Integer)stack.get(i);
					}
				}
				
			}
		}
		return sum;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str="(2+5)*3-(15+3)/3";
		char[] c=str.toCharArray();
		String pre=null;
		ArrayList<Object> list=new ArrayList<>();
		for(int i=0;i<c.length;++i){
			if(c[i]>='0'&&c[i]<='9'){
				if(pre==null){
					pre=String.valueOf(c[i]);
				}
				else{
					pre=pre+String.valueOf(c[i]);
				}
			}
			else{
				if(pre!=null){
					list.add(Integer.valueOf(pre));
					pre=null;
				}
				list.add(c[i]);
			}
		}
		if(pre!=null){
			list.add(Integer.valueOf(pre));
		}
		System.out.println(dfs(list, 0, list.size()-1));
	}

}

点赞