-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathLCS.java
More file actions
120 lines (101 loc) · 3.19 KB
/
LCS.java
File metadata and controls
120 lines (101 loc) · 3.19 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package DynamicProgramming;
public class LCS {
public static enum Direction {
H, V, O;
};
public class Paire {
public int cal;
public Direction d;
public Paire(int cal, Direction d) {
this.cal = cal;
this.d = d;
}
public Paire() {
this.cal = 0;
}
@Override
public String toString() {
return cal + "-" + d;
}
}
Paire[][] p;
String u, v;
public LCS(String u, String v) {
this.u = u;
this.v = v;
p = new Paire[u.length() + 1][v.length() + 1];
for (int i = 0; i < u.length() + 1; i++) {
for (int j = 0; j < v.length() + 1; j++) {
p[i][j] = new Paire();
}
}
}
public void init() {
for (int i = 1; i < u.length() + 1; i++) {
for (int j = 1; j < v.length() + 1; j++) {
if (u.charAt(i - 1) == v.charAt(j - 1)) {
p[i][j].cal = 1 + p[i - 1][j - 1].cal;
p[i][j].d = Direction.O;
} else if (p[i - 1][j].cal > p[i][j - 1].cal) {
p[i][j].cal = p[i - 1][j].cal;
p[i][j].d = Direction.V;
} else {
p[i][j].cal = p[i][j - 1].cal;
p[i][j].d = Direction.H;
}
}
}
}
public String result(int i, int j) {
if (p[i][j].cal == 0) {
return "";
}
if (p[i][j].d == Direction.O) {
return result(i - 1, j - 1) + u.charAt(i - 1);
}
if (p[i][j].d == Direction.H) {
return result(i, j - 1);
}
return result(i - 1, j);
}
public static String run(String u, String v){
LCS app = new LCS(u,v);
app.init();
return app.result(u.length(), v.length());
}
public void print() {
System.out.print("\t\t");
for (int i = 1; i < v.length() + 1; i++) {
System.out.print(v.charAt(i - 1) + "\t");
}
System.out.println("");
for (int i = 0; i < u.length() + 1; i++) {
if (i == 0) {
System.out.print("\t");
} else {
System.out.print(u.charAt(i - 1) + "\t");
}
for (int j = 0; j < v.length() + 1; j++) {
System.out.print(p[i][j] + "\t");
}
System.out.println("");
}
}
public static String doYouMean(String query, String[] text){
String result[] = new String[text.length];
for (int i = 0; i < text.length; i++) {
result[i] = LCS.run(query, text[i]);
}
int max = 0;
for (int i = 1; i < result.length; i++) {
if(result[max].length() < result[i].length())
max = i;
}
return text[max];
}
public static void main(String[] args) {
System.out.println(LCS.run("abcdbdab","bdcaba" ));
String dbText[] = new String[]{"house of cards", "game of throne", "breaking bad"};
System.out.println("Do you mean " + LCS.doYouMean("ga of Zrone", dbText));
}
}