- Notifications
You must be signed in to change notification settings - Fork 846
/
Copy path6.java
50 lines (40 loc) · 1.55 KB
/
6.java
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
importjava.util.*;
publicclassMain {
staticStringstr1;
staticStringstr2;
// 최소 편집 거리(Edit Distance) 계산을 위한 다이나믹 프로그래밍
staticinteditDist(Stringstr1, Stringstr2) {
intn = str1.length();
intm = str2.length();
// 다이나믹 프로그래밍을 위한 2차원 DP 테이블 초기화
int[][] dp = newint[n + 1][m + 1];
// DP 테이블 초기 설정
for (inti = 1; i <= n; i++) {
dp[i][0] = i;
}
for (intj = 1; j <= m; j++) {
dp[0][j] = j;
}
// 최소 편집 거리 계산
for (inti = 1; i <= n; i++) {
for (intj = 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]));
}
}
}
returndp[n][m];
}
publicstaticvoidmain(String[] args) {
Scannersc = newScanner(System.in);
Stringstr1 = sc.next();
Stringstr2 = sc.next();
// 최소 편집 거리 출력
System.out.println(editDist(str1, str2));
}
}