Skip to content

Commit 492b1c4

Browse files
committed
两道微小的题
1 parent 32249e9 commit 492b1c4

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

1143.最长公共子序列.java

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
* @lc app=leetcode.cn id=1143 lang=java
3+
*
4+
* [1143] 最长公共子序列
5+
*/
6+
7+
// @lc code=start
8+
class Solution {
9+
public int longestCommonSubsequence(String text1, String text2) {
10+
if(text1 == null || text1.length() == 0 || text2 == null || text2.length() == 0){
11+
return 0;
12+
}
13+
char[] str1 = text1.toCharArray();
14+
char[] str2 = text2.toCharArray();
15+
int n = str1.length;
16+
int m = str2.length;
17+
int[][] dp = new int[n][m];
18+
dp[0][0] = str1[0] == str2[0]?1:0;
19+
for(int i = 1;i<n;i++){
20+
dp[i][0] = str1[i] == str2[0]?1:dp[i-1][0];
21+
}
22+
for(int i = 1;i<m;i++){
23+
dp[0][i] = str1[0] == str2[i]?1:dp[0][i-1];
24+
}
25+
for(int i = 1; i < n;i++){
26+
for(int j = 1;j<m;j++){
27+
if(str1[i] == str2[j]){
28+
dp[i][j] = Math.max(dp[i][j],dp[i-1][j-1]+1);
29+
}else{
30+
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
31+
}
32+
}
33+
}
34+
return dp[n-1][m-1];
35+
}
36+
}
37+
// @lc code=end
38+

200.岛屿数量.java

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
* @lc app=leetcode.cn id=200 lang=java
3+
*
4+
* [200] 岛屿数量
5+
*/
6+
7+
// @lc code=start
8+
class Solution {
9+
public int numIslands(char[][] grid) {
10+
int count = 0;
11+
for(int i =0; i < grid.length;i++){
12+
for(int j = 0; j < grid[i].length;j++){
13+
if(grid[i][j] == '1'){
14+
dfs(grid, i, j);
15+
count++;
16+
}
17+
}
18+
}
19+
return count;
20+
}
21+
22+
private void dfs(char[][] grid, int i, int j){
23+
int n = grid.length;
24+
int m = grid[n].length;
25+
if(i < 0 || j<0 || i >=n||j>=m){
26+
return;
27+
}
28+
if(grid[i][j] == '0' || grid[i][j] == '2'){
29+
return;
30+
}
31+
grid[i][j] = '2';
32+
dfs(grid, i, j-1);
33+
dfs(grid, i, j+1);
34+
dfs(grid, i-1, j);
35+
dfs(grid, i+1, j);
36+
}
37+
}
38+
// @lc code=end
39+

0 commit comments

Comments
 (0)