您的位置:首页 > 其它

Basic Calculator

2015-12-04 12:46 134 查看
这道题目真是花了九牛二虎之力才做对。。。= = 先转成逆波兰式再计算。。。这里的版本是完整的计算器功能,包括所有运算符, I && II都适用。不多说了,心很累,直接上代码:

public class Solution {
public static int calculate(String s) {
if (s == null || s.length() == 0) {
return 0;
}

String str = s.replaceAll("\\s","");
List<String> postfix = convertToPostfix(str);
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < postfix.size(); i++) {
String current = postfix.get(i);
if (current.equals("+") || current.equals("-") || current.equals("*")
|| current.equals("/")) {
Integer num1 = stack.pop();
Integer num2 = stack.pop();
if (current.equals("-")) {
stack.push(num2-num1);
} else if (current.equals("+")) {
stack.push(num2 + num1);
} else if (current.equals("*")) {
stack.push(num2 * num1);
} else {
stack.push(num2 / num1);
}
} else {
stack.push(Integer.parseInt(current));
}
}
return stack.pop();
}

private static List<String> convertToPostfix(String str) {
Stack<Character> stack = new Stack<Character>();
List<String> list = new ArrayList<String>();
for (int i = 0; i < str.length(); i++) {
char current = str.charAt(i) ;
StringBuilder sb = new StringBuilder();
if (Character.isDigit(current)) {
while (i < str.length() && Character.isDigit(str.charAt(i))) {
sb.append(str.charAt(i));
i++;
}
i--;
list.add(sb.toString());
} else if (current == '(') {
stack.push(current);
} else if (current == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
list.add(Character.toString(stack.pop()));
}
stack.pop();
} else {
if (stack.isEmpty()) {
stack.push(current);
} else {
while (!stack.isEmpty()) {
char temp = stack.peek();
if (temp == '(' || (current == '*' && (temp == '+' || temp == '-'))
|| (current == '/' && (temp == '+' || temp == '-'))) {
break;
} else {
list.add(Character.toString(stack.pop()));
}
}
stack.push(current);
}
}
}

while (!stack.isEmpty()) {
list.add(Character.toString(stack.pop()));
}
return list;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string