题目:
计算输入字符串的值 “3 + 4 2 / 3 ”
思路:
用栈来存值
public class Solution {
public static int calculate(String s) {
char[] chars = s.trim().toCharArray();
LinkedList<Integer> numStack = new LinkedList<> ();
LinkedList<Character> opratorQueue = new LinkedList<> ();
int[] res = new int[1];
for(int i = 0 ; i < chars.length ;) {
char c = chars[i];
i++;
switch(c) {
case ' ' :
continue;
case '+' :
opratorQueue.add('+');
break;
case '-' :
opratorQueue.add('-');
break;
case '*' :
int pre = numStack.removeLast();
i = getNext(chars , i , res);
int next = res[0];
numStack.add(pre * next);
break;
case '/' :
int dpre = numStack.removeLast();
i = getNext(chars , i , res);
int dnext = res[0];
numStack.add(dpre / dnext);
break;
default :
i = getNext(chars , i-1 , res);
numStack.add(res[0]);
}
}
// System.out.println(numStack +" " +'\n' + opratorQueue);
while(!opratorQueue.isEmpty()) {
int pre = numStack.removeFirst();
int next = numStack.removeFirst();
char opra = opratorQueue.removeFirst();
if(opra == '+') numStack.addFirst(next + pre);
else numStack.addFirst(pre - next);
}
return numStack.getFirst();
}
// 不能以单个字符 表示一个数组 ,42就是两个字符
private static int getNext(char[] chars, int i , int[] res) {
String s = "";
for( ; i < chars.length ; i++) {
if(chars[i] == ' ') continue;
if(chars[i] == '+' || chars[i] == '-'
|| chars[i] == '*' || chars[i] == '/') break;
s += chars[i];
}
res[0] = Integer.parseInt(s);
return i;
}
}