牛客
统计相同字符串个数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.pfa;
import java.util.Scanner;
public class StrNumbers {
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); String a = scanner.nextLine(); StatisticStr(str, a);
}
static void StatisticStr(String str, String a) { String s = str.toLowerCase(); String a1 = a.toLowerCase(); System.out.println(s.length()-s.replaceAll(a1,"").length()); } }
|
明明的随机数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class RandomNumbers {
public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); TreeSet set = new TreeSet(); for(int i =0 ; i < num ;i++){ set.add(sc.nextInt()); }
Iterator iterator = set.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } }
}
|
5 进制转换
1 2 3 4 5 6 7 8
| public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); while (sc.hasNextLine()) { String s = sc.nextLine(); System.out.println(Integer.parseInt(s.substring(2), 16)); } }
|
力扣
面试
二角形最小路径
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| 给定一个二角形,找到从顶部到底部的最小路径和。每一步只能移动到下一行中相邻的数字。
例如,给定如下二角形:
[ [2], [3,4], [6,5,7], [4,1,8,3] ]
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
思路分析:
这道题可以用动态规划求解。我们定义一个二维数组 dp,其中 dp[i][j] 表示到达第 i 行第 j 列时的最小路径和,由于下一个数的选择范围只能在与自己相邻的下一级的两个数之间,因此状态转移方程如下:
dp[i][j] = min(dp[i-1][j], dp[i-1][j-1]) + triangle[i][j]
其中,triangle 是输入的二角形数据。
最终要求的是自顶向下的最小路径和,因此遍历完整个 triangle 二角形后,返回 dp[n-1][m-1] 即可。
代码实现:
public int minimumTotal(List<List<Integer>> triangle) { int n = triangle.size(); int m = triangle.get(n-1).size(); int[][] dp = new int[n][m]; dp[0][0] = triangle.get(0).get(0); for (int i = 1; i < n; i++) { dp[i][0] = dp[i-1][0] + triangle.get(i).get(0); for (int j = 1; j < i; j++) { dp[i][j] = Math.min(dp[i-1][j], dp[i-1][j-1]) + triangle.get(i).get(j); } dp[i][i] = dp[i-1][i-1] + triangle.get(i).get(i); } int res = Integer.MAX_VALUE; for (int i = 0; i < m; i++) { res = Math.min(res, dp[n-1][i]); } return res; }
|
深度优先遍历
思路是递归,访问顶点v后,继续以深度优先的方式访问其邻节点
广度优先遍历
思路是画弧,访问顶点v后,继续访问顶点v的所有邻节点,待其访问最后最后一邻节点,按顺序访问首次访问的邻节点的所有邻节点。依次进行。