Skip to content

Commit fcf9aa7

Browse files
committed
Longest Common Subsequence
1 parent aaf516a commit fcf9aa7

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// TC: O(n * m)
2+
// the length of text1 by the length of text2
3+
// SC: O(n)
4+
// both size of text1 and text2 can be the size of dp
5+
class Solution {
6+
public int longestCommonSubsequence(String text1, String text2) {
7+
int[] dp = new int[text2.length()];
8+
int output = 0;
9+
10+
for (char c : text1.toCharArray()) {
11+
int curLength = 0;
12+
13+
for (int i = 0; i < dp.length; i++) {
14+
if (curLength < dp[i]) curLength = dp[i];
15+
else if (c == text2.charAt(i)) {
16+
dp[i] = curLength + 1;
17+
output = Math.max(output, dp[i]);
18+
}
19+
}
20+
}
21+
return output;
22+
}
23+
}

0 commit comments

Comments
 (0)