Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commita22816d

Browse files
author
applewjg
committed
EditDistance
Change-Id: I82e3cd5a3bb94a55d55aa006d7d5c82932814b47
1 parent7b96e63 commita22816d

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

‎EditDistance.java

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 25, 2014
4+
Problem: Edit Distance
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/edit-distance/
7+
Notes:
8+
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
9+
You have the following 3 operations permitted on a word:
10+
a) Insert a character
11+
b) Delete a character
12+
c) Replace a character
13+
14+
Solution: Dynamic Programming.
15+
1. Time: O(mn) Space: O(mn)
16+
2. Time: O(mn) Space: O(n);
17+
*/
18+
publicclassSolution {
19+
publicintminDistance_1(Stringword1,Stringword2) {
20+
if(word1==word2)return0;
21+
intlen1 =word1.length();
22+
intlen2 =word2.length();
23+
int[][]dp =newint[len1+1][len2+1];
24+
25+
for(inti=0;i<=len1;i++)
26+
dp[i][0] =i;
27+
for(inti=0;i<=len2;i++)
28+
dp[0][i] =i;
29+
30+
for(inti=1;i<=len1;i++){
31+
for(intj=1;j<=len2;j++){
32+
if(word1.charAt(i-1)==word2.charAt(j-1))dp[i][j] =dp[i-1][j-1];
33+
else{
34+
dp[i][j] =Math.min(dp[i-1][j],Math.min(dp[i][j-1],dp[i-1][j-1]))+1;
35+
}
36+
}
37+
}
38+
returndp[len1][len2];
39+
}
40+
publicintminDistance(Stringword1,Stringword2) {
41+
if(word1==word2)return0;
42+
intlen1 =word1.length();
43+
intlen2 =word2.length();
44+
int[]dp =newint[len2+1];
45+
46+
for(inti=0;i<=len2;i++)
47+
dp[i] =i;
48+
49+
for(inti=1;i<=len1;i++){
50+
intupperLeftBak =dp[0];
51+
dp[0] =i;
52+
for(intj=1;j<=len2;j++){
53+
intupperLeft =upperLeftBak;
54+
upperLeftBak =dp[j];
55+
if(word1.charAt(i-1)==word2.charAt(j-1))dp[j] =upperLeft;
56+
else{
57+
dp[j] =Math.min(dp[j],Math.min(dp[j-1],upperLeft))+1;
58+
}
59+
}
60+
}
61+
returndp[len2];
62+
}
63+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp