Bootstrap

笔试算法总结

文章目录

题目1

在这里插入图片描述

使用 StringBuilder 模拟栈的行为,通过判断相邻2个字符是否相同,如果相同就进行删除

public class Main {
    public static String fun(String s) {
        if (s == null || s.length() <= 1) return s;

        StringBuilder builder = new StringBuilder(); // 使用StringBuilder模拟栈
        for (char c : s.toCharArray()) {
            if (builder.length() > 0 && builder.charAt(builder.length() - 1) == c) {
                builder.deleteCharAt(builder.length() - 1);
            } else {
                builder.append(c);
            }
        }

        return builder.toString();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        System.out.println(fun(s));
    }
}

题目2

在这里插入图片描述

public class Main {

    public static int climbStairs(int n) {
        if (n <= 2) {
            return n;
        }

        int[] dp = new int[n + 1]; // 动态规划数组

        dp[1] = 1;
        dp[2] = 2;

        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2]; // 状态转移方程
        }

        return dp[n];
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        System.out.println(climbStairs(n));
    }
}

题目3

在这里插入图片描述
在这里插入图片描述

 public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        int n = N;

        ArrayList<Integer> list = new ArrayList<>(N);
        while (n > 0) {
            list.add(scanner.nextInt());
            n -= 1;
        }

        ArrayList<Integer> list1 = new ArrayList<>(N);
        for (int i = 0; i < N; i++) {
            list1.add(0);
        }
        int res = 0;
        // 每次从每个口袋中取列表中最小值个糖果(0不管)
        while (!list1.equals(list)) {
            int min = Integer.MAX_VALUE;
            for (Integer i : list) {
                if (i == 0) continue;
                if (i < min) min = i;
            }

            for (int i = 0; i < list.size(); i++) {
                if (list.get(i) == 0) continue;
                list.set(i, list.get(i) - min);
            }

            res+=1;
        }
        System.out.println(res);
    }
}
;