赞
踩
题目描述:
https://leetcode-cn.com/problems/basic-calculator/
Java代码:
- class Solution { //数字、+-、()、空格
- public int calculate(String s) {
- char[] a=new char[s.length()+1];//a[a.length-1]为'\0',充当边界屏障
- int ans=0,top=0,slen=s.length(),num=0,operand=1,ai=0;//top为栈指针,operand为当前操作数的直接符号(操作数的正负还结结合父括号的正负来判断))
- for(int si=0;si<slen;si++)if(s.charAt(si)!=' ')a[ai++]=s.charAt(si);
- int[] operandStack=new int[ai];//1表示正,-1表示负
- operandStack[0]=1;//[0]为默认值1,表示栈底(避免对栈底进行单独处理))
- for(int i=0;i<ai;i++){
- if(a[i]>='0'){//本题a[i]>='0'即可判断是数字字符
- num=a[i]-'0'+num*10;//要防溢出
- if(a[i+1]<'0'){ //i+1要防越界
- ans+=num*operand*operandStack[top];
- num=0;
- operand=1;
- }
- }else if(a[i]=='('){
- operandStack[top+1]=operandStack[top++]*operand;//之后top++
- operand=1;
- }else if(a[i]==')')top--;
- else if(a[i]=='-')operand=-operand;
- }
- return ans;
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。