File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
longest-common-subsequence Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int longestCommonSubsequence (String text1 , String text2 ) {
3
+ int m = text1 .length ();
4
+ int n = text2 .length ();
5
+
6
+ int [][] dp = new int [m +1 ][n +1 ];
7
+
8
+ for (int i = 0 ; i < m ; i ++) {
9
+ for (int j = 0 ; j < n ; j ++) {
10
+ // DP ๊ณ์ฐ์ +1๋ก ํ์ด์ผ ํ๋๋ฐ ์ด์ ์ผ์ด์ค๋ฅผ ์ฌ์ฌ์ฉํ๋ -1๋ก๋ง ์ ๊ทผํด์ ๋ฒ์ ์๋ฌ๊ฐ ๋ง์ด ๋ฌ์๋ค.
11
+ if (text1 .charAt (i ) == text2 .charAt (j )) {
12
+ dp [i + 1 ][j + 1 ] = dp [i ][j ] + 1 ;
13
+ } else {
14
+ dp [i + 1 ][j + 1 ] = Math .max (dp [i ][j + 1 ], dp [i + 1 ][j ]);
15
+ }
16
+ }
17
+ }
18
+
19
+ return dp [m ][n ];
20
+ }
21
+
22
+ // -1์ ์ฐธ์กฐํด ์ด์ ์ผ์ด์ค๋ฅผ ์ฌ์ฌ์ฉํ๋ ๊ฒฝ์ฐ๋ 1๋ถํฐ m,n๊น์ง ํ๋ฉด ๊ทธ๋ ๊ฒ ํ ์ ์๋ค.
23
+ public int longestCommonSubsequence2 (String text1 , String text2 ) {
24
+ int m = text1 .length ();
25
+ int n = text2 .length ();
26
+ int [][] dp = new int [m + 1 ][n + 1 ];
27
+
28
+ for (int i = 1 ; i <= m ; i ++) {
29
+ for (int j = 1 ; j <= n ; j ++) {
30
+ if (text1 .charAt (i - 1 ) == text2 .charAt (j - 1 )) {
31
+ dp [i ][j ] = dp [i - 1 ][j - 1 ] + 1 ; // ๋ฌธ์๊ฐ ๊ฐ์ผ๋ฉด ๋๊ฐ์ ๊ฐ + 1
32
+ } else {
33
+ dp [i ][j ] = Math .max (dp [i - 1 ][j ], dp [i ][j - 1 ]); // ์ or ์ผ์ชฝ ์ค ํฐ ๊ฐ
34
+ }
35
+ }
36
+ }
37
+
38
+ return dp [m ][n ];
39
+ }
40
+ }
You canโt perform that action at this time.
0 commit comments