File tree 2 files changed +84
-0
lines changed
longest-common-subsequence
2 files changed +84
-0
lines changed Original file line number Diff line number Diff line change
1
+ package leetcode_study
2
+
3
+ /*
4
+ * 링크드 리스트에서 순환이 발생하는지 체크하는 문제
5
+ * Node `val` 값을 주어진 범위 (-10,000 <= `val` <= 10,000) 보다 큰 정수로 변경해 cycle 판별 시도
6
+ * 시간 복잡도: O(n)
7
+ * -> linked list node 개수만큼 진행
8
+ * 공간 복잡도: O(1)
9
+ * -> 주어진 node를 가리키는 currentNode 이외에 추가되는 없음
10
+ * */
11
+ fun hasCycle (head : ListNode ? ): Boolean {
12
+ var currentNode = head
13
+
14
+ while (currentNode?.next != null ) {
15
+ if (currentNode.`val ` == 10001 ) return true // 이미 방문한 노드이면 사이클 존재
16
+ currentNode.`val ` = 10001 // 방문한 노드 표시
17
+ currentNode = currentNode.next // 다음 노드로 이동
18
+ }
19
+
20
+ return false // `null`을 만났다면 사이클 없음
21
+ }
Original file line number Diff line number Diff line change
1
+ package leetcode_study
2
+
3
+ /*
4
+ * 가장 긴 공통 부분 문자열의 길이를 구하는 문제
5
+ * 동적 계획법을 사용한 문제 해결
6
+ * 문자가 동일할 경우, table[i][j] = table[i-1][j-1] + 1. 즉, 이전까지의 최장 공통 부분 문자열 길이에 1을 추가
7
+ * 문자가 다를 경우, table[i][j] = max(table[i-1][j], table[i][j-1]) 이는 현재까지 찾은 최장 공통 부분 문자열의 길이를 유지하는 과정
8
+ *
9
+ * 시간 복잡도: O(n^2)
10
+ * -> 두 분자열을 이중 반복을 진행하는 경우
11
+ * 공간 복잡도: O(nm) (= n과 m은 각각 주어진 문자열을 길이)
12
+ * -> dp table에 사용되는 공간
13
+ * */
14
+ fun longestCommonSubsequence (text1 : String , text2 : String ): Int {
15
+ val n = text1.length
16
+ val m = text2.length
17
+ val dp = Array (n + 1 ) { IntArray (m + 1 ) }
18
+
19
+ for (i in 1 .. n) {
20
+ for (j in 1 .. m) {
21
+ if (text1[i - 1 ] == text2[j - 1 ]) {
22
+ dp[i][j] = dp[i - 1 ][j - 1 ] + 1
23
+ } else {
24
+ dp[i][j] = maxOf(dp[i - 1 ][j], dp[i][j - 1 ])
25
+ }
26
+ }
27
+ }
28
+ return dp[n][m]
29
+ }
30
+
31
+ /*
32
+ * 주어진 두 문자열에 각각의 Index를 두어 비교해가며 해결 시도 해당 방법으로 시도
33
+ * Test case를 통과했지만 "bac", "abc"와 같은 case에서 "bc"를 답으로 도출할 수 있지만 "ac"와 같은 경우는 지나치게됨
34
+ * 즉, 정답이 되는 경우를 제외할 수 있음.
35
+ * */
36
+ fun longestCommonSubsequence (text1 : String , text2 : String ): Int {
37
+ var result = 0
38
+ var longOne: String
39
+ var shortOne: String
40
+ var longIndex = 0
41
+ var shortIndex = 0
42
+
43
+ if (text1.length >= text2.length) {
44
+ longOne = text1
45
+ shortOne = text2
46
+ } else {
47
+ longOne = text2
48
+ shortOne = text1
49
+ }
50
+
51
+ while (shortIndex < shortOne.length) {
52
+ if (shortOne[shortIndex] == longOne[longIndex]) {
53
+ shortIndex + = 1
54
+ longIndex + = 1
55
+ result + = 1
56
+ } else {
57
+ longIndex + = 1
58
+ }
59
+ if (longIndex == longOne.length) break
60
+ }
61
+
62
+ return result
63
+ }
You can’t perform that action at this time.
0 commit comments