Skip to content

Commit c547bf2

Browse files
solves longest common subsequence
1 parent 5eb3f90 commit c547bf2

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,7 @@
306306
| 1133 | 🔒 [Largest Unique Number](https://leetcode.com/problems/largest-unique-number) | | |
307307
| 1134 | 🔒 [Armstrong Number](https://leetcode.com/problems/armstrong-number) | | |
308308
| 1137 | [Nth Tribonacci Number](https://leetcode.com/problems/n-th-tribonacci-number) | [![Java](assets/java.png)](src/NthTribonacciNumber.java) | |
309+
| 1143 | [Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence) | [![Java](assets/java.png)](src/LongestCommonSubsequence.java) | |
309310
| 1150 | [Check if Number is Majority Element in Sorted Array](https://leetcode.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array) | | |
310311
| 1154 | [Day of The Year](https://leetcode.com/problems/day-of-the-year) | [![Java](assets/java.png)](src/DayOfTheYear.java) | |
311312
| 1160 | [Find Words That Can Be Formed By Characters](https://leetcode.com/problems/find-words-that-can-be-formed-by-characters) | | |

src/LongestCommonSubsequence.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
public class LongestCommonSubsequence {
2+
public int longestCommonSubsequence(String text1, String text2) {
3+
final int[][] memory = new int[2][text2.length()];
4+
final int rows = text1.length(), columns = text2.length();
5+
6+
// first row, first column
7+
memory[0][0] = text1.charAt(0) == text2.charAt(0) ? 1 : 0;
8+
9+
// first row
10+
for (int column = 1 ; column < columns ; column++) {
11+
memory[0][column] = text2.charAt(column) == text1.charAt(0) ? 1 : memory[0][column - 1];
12+
}
13+
14+
int i = 1;
15+
// rest of table
16+
for (int row = 1 ; row < rows ; row++, i ^= 1) {
17+
for (int column = 0 ; column < text2.length() ; column++) {
18+
if (column == 0) {
19+
memory[i][column] = text1.charAt(row) == text2.charAt(0) ? 1 : memory[i ^ 1][column];
20+
} else {
21+
memory[i][column] = max(
22+
memory[i][column - 1],
23+
memory[i ^ 1][column],
24+
text1.charAt(row) == text2.charAt(column) ? 1 + memory[i ^ 1][column - 1] : 0
25+
);
26+
}
27+
}
28+
}
29+
return memory[i ^ 1][columns - 1];
30+
}
31+
32+
private int max(int... values) {
33+
int result = 0;
34+
for (int value : values) {
35+
result = Math.max(result, value);
36+
}
37+
return result;
38+
}
39+
}

0 commit comments

Comments
 (0)