中级农民
- 积分
- 210
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-6-23
- 最后登录
- 1970-1-1
|
感谢楼主的面经!
第三题我写了个有点长的,抛砖引玉,expression tree 应该可以
- public class expressionTree {
- class Node {
- Node left;
- Node right;
- int val;
- String str;
- Node(int val, String str) {
- this.val = val;
- this.str = str;
- }
- }
- @Test
- public void testP() {
- System.out.println(removeDuplicateParentheses("(1+2)*3"));
- System.out.println(removeDuplicateParentheses("(1*3)+2"));
- System.out.println(removeDuplicateParentheses("(1+3)+2"));
- System.out.println(removeDuplicateParentheses("(1+3)-2"));
- System.out.println(removeDuplicateParentheses("(1-3)+(3-2)"));
- System.out.println(removeDuplicateParentheses("(1-3)+(3-6)*(3-2)"));
- }
- public String removeDuplicateParentheses(String exp) {
- exp = exp.replaceAll("\\s+", "");
- int base = 0;
- Stack<Node> stack = new Stack<>(); // increasing
-
- for (int i = 0; i < exp.length(); i++) {
- Node node = null;
- if (exp.charAt(i) == '(') {
- base += 10;
- continue;
- } else if (exp.charAt(i) == ')') {
- base -= 10;
- continue;
- } else if (Character.isDigit(exp.charAt(i))) {
- int num = exp.charAt(i) - '0';
- while (i + 1 < exp.length() && Character.isDigit(exp.charAt(i + 1))) {
- num = num * 10 + exp.charAt(i + 1);
- i = i + 1;
- }
- node = new Node(Integer.MAX_VALUE, String.valueOf(num));
- } else {
- int opVal = getOpVal(exp.charAt(i), base);
- node = new Node(opVal, String.valueOf(exp.charAt(i)));
- }
-
- while (!stack.isEmpty() && stack.peek().val >= node.val) {
- node.left = stack.pop();
- }
- if (!stack.isEmpty()) {
- stack.peek().right = node;
- }
- stack.push(node);
- }
-
- Node root = null;
- while (!stack.isEmpty()) {
- root = stack.pop();
- }
- return helper(root);
- }
- private String helper(Node root) {
- if (root == null) {
- return "";
- }
- if (root.left == null && root.right == null) {
- return root.str;
- }
- String left = helper(root.left);
- String right = helper(root.right);
- if (getOp(root.str) > getOp(root.left.str)) {
- // (1+1)-2 not add.
- // (1+1)*2 add
- left = "(" + left + ")";
- }
- if (getOp(root.str) >= getOp(root.right.str)) { // 1+(1-3) add
- right = "(" + right + ")";
- }
- return left + root.str + right;
-
- }
- private int getOp(String opStr) {
- if (opStr.equals("+") || opStr.equals("-")) {
- return 1;
- }
- if (opStr.equals("*") || opStr.equals("/")) {
- return 2;
- }
- // otherwise make it really big
- return Integer.MAX_VALUE;
- }
- private int getOpVal(char c, int base) {
- if (c == '+' || c == '-') {
- return base + 1;
- } else {
- return base + 2;
- }
- }
- }
复制代码 |
|