问题:
解题:
分析:首先需要拆分指令和数字,指令有两个层级,先乘除再加减;需要先把乘除的两个数字计算出并替换为一个数字;两个思路,先把符号和数字,有序的表示出来,再跟进顺序遍历,先计算加减,遇到加减将相邻的数字合并成一个,可以用链表,不过两个层级需要遍历三遍;第二个思路就是一共就两个层级,索性就在或者去数字符号的时候就进行计算,遇到-就把之后的数字变成负数,遇到乘除就进行计算,然后最后求和,两次遍历解决,比较快,用数组应该更快
class Solution {
private static final char JIA = '+';
private static final char JIAN = '-';
private static final char CHENG = '*';
private static final char CHU = '/';
public int calculate(String s) {
char[] chars = s.toCharArray();
Stack<Integer> stackInt = new Stack<>();
// 解析数字和符号
int tempNum = 0;
char tempChar = '+';
for (char aChar : chars) {
switch (aChar) {
case JIA:
case JIAN:
case CHENG:
case CHU:
// 符号
// 若是符号,转换乘除和减
chuLi(tempNum, tempChar, stackInt);
tempNum = 0;
tempChar = aChar;
break;
default:
// 数字
if (aChar >= '0' && aChar <= '9') {
tempNum = tempNum * 10 + (aChar - '0');
}
break;
}
}
// 最后一个数字
chuLi(tempNum, tempChar, stackInt);
// 计算
int res = 0;
while (!stackInt.empty()) {
res += stackInt.pop();
}
return res;
}
private void chuLi(int tempNum, char tempChar, Stack<Integer> stackInt) {
switch (tempChar) {
case JIA:
stackInt.push(tempNum);
break;
case JIAN:
stackInt.push(-tempNum);
break;
case CHENG:
stackInt.push(stackInt.pop() * tempNum);
break;
case CHU:
stackInt.push(stackInt.pop() / tempNum);
break;
default:
}
}
}
class Solution {
private static final char JIA = '+';
private static final char JIAN = '-';
private static final char CHENG = '*';
private static final char CHU = '/';
public int calculate(String s) {
char[] chars = s.toCharArray();
int[] stackInt = new int[s.length()];
int[] index = {0};
//LinkedList<Integer> stackInt = new LinkedList<>();
// 解析数字和符号
int tempNum = 0;
char tempChar = '+';
for (char aChar : chars) {
switch (aChar) {
case JIA:
case JIAN:
case CHENG:
case CHU:
// 符号
// 若是符号,转换乘除和减
chuLi(tempNum, tempChar, stackInt, index);
tempNum = 0;
tempChar = aChar;
break;
default:
// 数字
if (aChar >= '0' && aChar <= '9') {
tempNum = tempNum * 10 + (aChar - '0');
}
break;
}
}
// 最后一个数字
chuLi(tempNum, tempChar, stackInt, index);
// 计算
int res = 0;
while (0 != index[0]) {
res += pop(stackInt, index);
}
return res;
}
private void push(int[] stackInt, int[] index, int value) {
stackInt[index[0]] = value;
index[0] = ++index[0];
}
private int pop(int[] stackInt, int[] index) {
index[0] = --index[0];
return stackInt[index[0]];
}
private void chuLi(int tempNum, char tempChar, int[] stackInt, int[] index) {
switch (tempChar) {
case JIA:
push(stackInt, index, tempNum);
break;
case JIAN:
push(stackInt, index, -tempNum);
break;
case CHENG:
push(stackInt, index, pop(stackInt, index) * tempNum);
break;
case CHU:
push(stackInt, index, pop(stackInt, index) / tempNum);
break;
default:
}
}
}
性能:
数组确实快啊,不过占用空间还不是最小的