腾讯一面题目及自己的答案

1 输入一个数组表示台阶的高度,台阶槽之间可以积水,请问能积多少水

    public static void main(String args[]) {
        System.out.println(calculateUsedNum(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}));
    }

    private static int calculateUsedNum(int[] graps) {
        int size = graps.length;
        //寻找存在 下陷区间的数据
        int result = 0;
        int startIndex = 1;
        int sdd = 0;
        for (int i = 0; i < size; i++) {
            int current = graps[i];
            int startGrap;

            for (int j = i + 1; j < size; j++) {
                startGrap = graps[j];
                if (startGrap > current) {
                    startIndex = j;
                    i = j;
                    sdd = graps[j];
                    break;
                }
            }

            for (int m = startIndex; m < size; m++) {
                if (graps[m] > sdd) {
                    for (int s = startIndex; s <= m; s++) {
                        result = result + (sdd - graps[s]);
                    }
                    sdd = graps[m];
                    i = m;
                    startIndex = m + 1;
                }
            }

        }
        return result;
    }

2 输入括号对,检查是否成对


    public static void main(String args[]) {
        System.out.println(searchKh("()"));
        System.out.println(searchKh("()[]{}"));
        System.out.println(searchKh("(]"));
        System.out.println(searchKh("([)]"));
        System.out.println(searchKh("{[]}"));
    }

 private static boolean searchKh(String str) {
        Map khMap = new HashMap<>();
        khMap.put(')', '(');
        khMap.put('}', '{');
        khMap.put(']', '[');
        char[] strArr = str.toCharArray();
        int size = strArr.length;
        Stack stack = new Stack<>();
        boolean result = true;
        for (int i = 0; i < size; i++) {
            if (!result) {
                break;
            }
            char current = strArr[i];
            if (i == 0 && (current == ')' || current == '}' || current == ']')) {
                result = false;
            }

            if (current == '(' || current == '{' || current == '[') {
                stack.push(current);
            }
            if (current == ')' || current == '}' || current == ']') {
                if (stack.pop() != khMap.get(current)) {
                    result = false;
                }
            }
        }
        return result;
    }

你可能感兴趣的:(腾讯一面题目及自己的答案)