Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
Example 1:
Input: "1 + 1"
Output: 2
Example 2:
Input: " 2-1 + 2 "
Output: 3
Example 3:
Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23
Note:
You may assume that the given expression is always valid.
Do not use the eval built-in library function.
反正大概意思是我输入一串字符串,里面可能有数字(0-9),+,-,左括号,右括号以及空格符号,给出一个算法求解这个字符串的结果.所有的分析过程和步骤我都写在注释里面了.
public static int calculate(String s) {
/*思路就是只需要知道一对括号外面的符号,我们就知道所有括号内数字的正确符号*/
/*我们令flag=1表示正号,flag=0表示负号,无符号用flag=1表示*/
int flag = 1;
int curretnFlag = 1;
int result = 0;
Stack<Integer> flagStack = new Stack<Integer>();//记录每个一个括号外的符号
for(int i = 0; i< s.length(); i++){
char ch = s.charAt(i);
if(ch=='('){//括号开始的地方,判断上一个字符是什么符号
if(i-1>=0){//上一个字符存在
if(s.charAt(i-1)=='-')curretnFlag=0;//负号则flag=0;
else curretnFlag=1;//正号则flag=1;
}else{//不存在即无符号
curretnFlag = 1;
}
//由当前括号之前的flag和当前括号的curretnFlag共同构成当前括号正确符号(同或)
flagStack.push(curretnFlag);
flag = (flag^curretnFlag)^1;
}else if(ch==' '){//题干中说明可能或存在空格,如果是空格则直接跳过
continue;
}else if(ch>='0'&&ch<='9'){//如果是数字,需将数字前的符号和当前括号的符号联系起来判断当前数字的正确符号
int numFlag = 1;//默认是无符号
if(i-1>=0){
if(s.charAt(i-1)=='-')numFlag=0;
else numFlag=1;
}
numFlag = (flag^numFlag)^1;
//(出现连续数字的情况)
StringBuilder sb = new StringBuilder();
while(i<s.length()&&s.charAt(i)>='0'&&s.charAt(i)<='9'){
sb.append(s.charAt(i));
i++;//向前推进
}
i--;
if(numFlag==1)result+=Integer.valueOf(sb.toString());
else result-=Integer.valueOf(sb.toString());
}else if(ch==')'){//当前字符为')',我们需要将符号还原到当前括号之前的正确符号(同或)
flag = (flag^flagStack.pop())^1;
}else{//
}
}
return result;
}
时间复杂度为Θ(n).