File tree Expand file tree Collapse file tree 3 files changed +13
-11
lines changed
longest-common-subsequence Expand file tree Collapse file tree 3 files changed +13
-11
lines changed Original file line number Diff line number Diff line change
1
+ // A: node 의 갯수, B: neighbors의 길이
2
+ // 시간복잡도: O(A + B)
3
+ // 공간복잡도: O(A + B)
4
+
1
5
package main
2
6
3
7
import "testing"
Original file line number Diff line number Diff line change @@ -26,21 +26,19 @@ func Test_longestCommonSubsequence(t *testing.T) {
26
26
}
27
27
28
28
func longestCommonSubsequence (text1 string , text2 string ) int {
29
- commonSubsequence := make ([][]int , len (text1 )+ 1 )
29
+ prev := make ([]int , len (text2 )+ 1 )
30
+ curr := make ([]int , len (text2 )+ 1 )
30
31
31
- for i := 0 ; i < len (text1 )+ 1 ; i ++ {
32
- commonSubsequence [i ] = make ([]int , len (text2 )+ 1 )
33
- }
34
-
35
- for i := 1 ; i < len (text1 )+ 1 ; i ++ {
36
- for j := 1 ; j < len (text2 )+ 1 ; j ++ {
32
+ for i := 1 ; i <= len (text1 ); i ++ {
33
+ for j := 1 ; j <= len (text2 ); j ++ {
37
34
if text1 [i - 1 ] == text2 [j - 1 ] {
38
- commonSubsequence [ i ][ j ] = commonSubsequence [ i - 1 ] [j - 1 ] + 1
35
+ curr [ j ] = prev [j - 1 ] + 1
39
36
} else {
40
- commonSubsequence [ i ][ j ] = max (commonSubsequence [ i - 1 ][ j ], commonSubsequence [ i ] [j - 1 ])
37
+ curr [ j ] = max (prev [ j ], curr [j - 1 ])
41
38
}
42
39
}
40
+ prev , curr = curr , prev
43
41
}
44
42
45
- return commonSubsequence [ len ( text1 )] [len (text2 )]
43
+ return prev [len (text2 )]
46
44
}
Original file line number Diff line number Diff line change 1
- // 시간복잡도: O(1 )
1
+ // 시간복잡도: O(log n )
2
2
// 공간복잡도: O(1)
3
3
4
4
package main
You can’t perform that action at this time.
0 commit comments