import
java.util.*;
class
FollowUp_PrintAllPossibleChanges {
int
[][] dp;
List<List<String> > allWays =
new
ArrayList<>();
int
minDistance(String s, String targ) {
int
m = s.length(), n = targ.length();
dp =
new
int
[m +
1
][n +
1
];
for
(
int
i =
0
; i <= m; i++) dp[i][
0
] = i;
for
(
int
j =
0
; j <= n; j++) dp[
0
][j] = j;
for
(
int
i =
1
; i <= m; i++)
for
(
int
j =
1
; j <= n; j++)
if
(s.charAt(i -
1
) == targ.charAt(j -
1
)) dp[i][j] = dp[i -
1
][j -
1
];
else
dp[i][j] =
1
+ Math.min(dp[i -
1
][j -
1
], Math.min(dp[i -
1
][j], dp[i][j -
1
]));
return
dp[m][n];
}
void
printAllChanges(String s, String t, List<String> changes) {
int
i = s.length(), j = t.length();
while
(i >
0
&& j >
0
) {
if
(s.charAt(i -
1
) == t.charAt(j -
1
)) { i--; j--; }
else
{
boolean
replaced =
false
, deleted =
false
;
int
nextI = i, nextJ = j;
if
(dp[i][j] == dp[i -
1
][j -
1
] +
1
) {
changes.add(s.charAt(i -
1
) +
"->"
+ t.charAt(j -
1
));
nextI = i -
1
; nextJ = j -
1
; replaced =
true
;
}
if
(dp[i][j] == dp[i -
1
][j] +
1
) {
if
(!replaced) { changes.add(
"Del "
+ s.charAt(i -
1
)); nextI = i -
1
; }
else
{
var changes2 =
new
ArrayList<>(changes);
changes2.remove(changes.size() -
1
);
changes2.add(
"Del "
+ s.charAt(i -
1
));
printAllChanges(s.substring(
0
, i -
1
), t.substring(
0
, j), changes2);
}
deleted =
true
;
}
if
(dp[i][j] == dp[i][j -
1
] +
1
) {
if
(!replaced && !deleted) { changes.add(
"Add "
+ t.charAt(j -
1
)); nextJ = j -
1
; }
else
{
var changes2 =
new
ArrayList<>(changes);
changes2.remove(changes.size() -
1
);
changes2.add(
"Add "
+ t.charAt(j -
1
));
printAllChanges(s.substring(
0
, i), t.substring(
0
, j -
1
), changes2);
}
}
i = nextI; j = nextJ;
}
}
while
(i >
0
) changes.add(
"Del "
+ s.charAt(--i));
while
(j >
0
) changes.add(
"Add "
+ t.charAt(--j));
allWays.add(changes);
}
void
printWays(String s1, String s2) {
printAllChanges(s1, s2,
new
ArrayList<>());
int
i =
1
;
for
(var way : allWays) {
System.out.print(
"Method #"
+ i++ +
": "
);
System.out.println(String.join(
", "
, way));
}
}
public
static
void
main(String[] args)
throws
Exception {
var o =
new
FollowUp_PrintAllPossibleChanges();
o.minDistance(
"abcdef"
,
"axcdfdh"
);
o.printWays(
"abcdef"
,
"axcdfdh"
);
o =
new
FollowUp_PrintAllPossibleChanges();
o.minDistance(
""
,
"abc"
);
o.printWays(
""
,
"abc"
);
o =
new
FollowUp_PrintAllPossibleChanges();
o.minDistance(
"abc"
,
""
);
o.printWays(
"abc"
,
""
);
}
}