在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Leetcode[224] Basic Calculator

2016-12-20 13:12| 发布者: zhangjf| 查看: 531| 评论: 0

摘要: Leetcode Basic Calculator Implement a basic calculator to evaluate a simple expression string. The expression string may contain open ( and closing parentheses ),the plus +, minus sign - or * or /, n ...
Leetcode[224] Basic Calculator

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ),
the plus +, minus sign - or * or /, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

  1. "1 + 1" = 2
  2. " 2-1 + 2 " = 3
  3. "(1+(4+5+2)-3)+(6+8)" = 23
  4. "1 + (2 - 3 * 4)" = -9;
复制代码
Stack

复杂度
O(N), O(N)

思路
将字符串先转换成后缀表达式,再将其evaluate出来。
前后缀表达式的转换:
http://scriptasylum.com/tutor...
后缀表达式的evaluation:
http://scriptasylum.com/tutor...

代码

  1. public int basicCalculator(String s) {
  2. s = s.trim().replaceAll(" +", "");
  3. Stack<Character> stack = new Stack<>();
  4. StringBuilder builder = new StringBuilder();
  5. char[] arr = s.toCharArray();
  6. for(int i = 0; i < arr.length; i ++) {
  7. if(arr[i] == '(') {
  8. stack.push('(');
  9. }
  10. else if(arr[i] == ')') {
  11. while(!stack.isEmpty() && stack.peek() != '(') {
  12. builder.append(stack.pop());
  13. }
  14. // pop out the '('
  15. stack.pop();
  16. }
  17. else if(Character.isDigit(arr[i])) {
  18. int val = 0;
  19. for(int j = i; j < arr.length && Character.isDigit(arr[j]); j ++) {
  20. val *= 10;
  21. val += arr[j] - '0';
  22. }
  23. builder.append(val);
  24. i = j - 1;
  25. }
  26. else {
  27. while(!stack.isEmpty() && rank(stack.peek()) >= rank(arr[j])) {
  28. builder.append(stack.pop());
  29. }
  30. stack.push(arr[j]);
  31. }
  32. }
  33. while(!stack.isEmpty()) {
  34. builder.append(stack.pop());
  35. }
  36. return evaluate(builder.toString());
  37. }
  38. public int rank(Character ch) {
  39. if(ch == '+' || ch == '-') return 1;
  40. else if(ch == '*' || ch == '/') return 2;
  41. // '('
  42. return 0;
  43. }
  44. public int evaluate(String s) {
  45. char[] arr = s.toCharArray();
  46. Stack<Integer> stack = new Stack<>();
  47. for(int i = 0; i < arr.length; i ++) {
  48. if(Character.isDigit(arr[i])) {
  49. stack.push(arr[i] - '0');
  50. }
  51. else {
  52. int op2 = stack.pop();
  53. int op1 = stack.pop();
  54. if(arr[i] == '+') {
  55. stack.push(op1 + op2);
  56. }
  57. else if(arr[i] == '-') {
  58. stack.push(op1 - op2);
  59. }
  60. else if(arr[i] == '*') {
  61. stack.push(op1 * op2);
  62. }
  63. else {
  64. stack.push(op1 / op2);
  65. }
  66. }
  67. }
  68. return stack.pop();
  69. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-7 20:14

Copyright 2015-2025 djqfx

返回顶部