forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path6.java
More file actions
50 lines (40 loc) ยท 1.55 KB
/
6.java
File metadata and controls
50 lines (40 loc) ยท 1.55 KB
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
40
41
42
43
44
45
46
47
48
49
50
import java.util.*;
public class Main {
static String str1;
static String str2;
// ์ต์ ํธ์ง ๊ฑฐ๋ฆฌ(Edit Distance) ๊ณ์ฐ์ ์ํ ๋ค์ด๋๋ฏน ํ๋ก๊ทธ๋๋ฐ
static int editDist(String str1, String str2) {
int n = str1.length();
int m = str2.length();
// ๋ค์ด๋๋ฏน ํ๋ก๊ทธ๋๋ฐ์ ์ํ 2์ฐจ์ DP ํ
์ด๋ธ ์ด๊ธฐํ
int[][] dp = new int[n + 1][m + 1];
// DP ํ
์ด๋ธ ์ด๊ธฐ ์ค์
for (int i = 1; i <= n; i++) {
dp[i][0] = i;
}
for (int j = 1; j <= m; j++) {
dp[0][j] = j;
}
// ์ต์ ํธ์ง ๊ฑฐ๋ฆฌ ๊ณ์ฐ
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
// ๋ฌธ์๊ฐ ๊ฐ๋ค๋ฉด, ์ผ์ชฝ ์์ ํด๋นํ๋ ์๋ฅผ ๊ทธ๋๋ก ๋์
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
}
// ๋ฌธ์๊ฐ ๋ค๋ฅด๋ค๋ฉด, ์ธ ๊ฐ์ง ๊ฒฝ์ฐ ์ค์์ ์ต์๊ฐ ์ฐพ๊ธฐ
else { // ์ฝ์
(์ผ์ชฝ), ์ญ์ (์์ชฝ), ๊ต์ฒด(์ผ์ชฝ ์) ์ค์์ ์ต์ ๋น์ฉ์ ์ฐพ์ ๋์
dp[i][j] = 1 + Math.min(dp[i][j - 1], Math.min(dp[i - 1][j], dp[i - 1][j - 1]));
}
}
}
return dp[n][m];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.next();
String str2 = sc.next();
// ์ต์ ํธ์ง ๊ฑฐ๋ฆฌ ์ถ๋ ฅ
System.out.println(editDist(str1, str2));
}
}