|
| 1 | +package leetcode_study |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | +import kotlin.math.max |
| 6 | + |
| 7 | +class `longest-repeating-character-replacement` { |
| 8 | + |
| 9 | + fun characterReplacement(s: String, k: Int): Int { |
| 10 | + return usingSlidingWindow(s, k) |
| 11 | + } |
| 12 | + |
| 13 | + /** |
| 14 | + * TC: O(n^3), SC: O(1) 시간초과 !!! |
| 15 | + */ |
| 16 | + private fun usingBruteForce(s: String, k: Int): Int { |
| 17 | + var result = 0 |
| 18 | + |
| 19 | + for (start in s.indices) { |
| 20 | + for (end in start until s.length) { |
| 21 | + val counter = mutableMapOf<Char, Int>() |
| 22 | + for (i in start .. end) { |
| 23 | + counter[s[i]] = counter.getOrDefault(s[i], 0) + 1 |
| 24 | + } |
| 25 | + |
| 26 | + val maxCount = counter.values.maxOrNull() ?: 0 |
| 27 | + if ((end - start + 1) - maxCount <= k) { |
| 28 | + result = max(result, end - start + 1) |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + return result |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * TC: O(n), SC: O(1) |
| 38 | + */ |
| 39 | + private fun usingSlidingWindow(s: String, k: Int): Int { |
| 40 | + var (maxLength, start) = 0 to 0 |
| 41 | + val count = IntArray(26) |
| 42 | + |
| 43 | + for (end in s.indices) { |
| 44 | + count[s[end] - 'A']++ |
| 45 | + while (end - start + 1 - count.max() > k) { |
| 46 | + count[s[start] - 'A']-- |
| 47 | + start++ |
| 48 | + } |
| 49 | + maxLength = max(end - start + 1, maxLength) |
| 50 | + } |
| 51 | + |
| 52 | + return maxLength |
| 53 | + } |
| 54 | + |
| 55 | + @Test |
| 56 | + fun `문자열이 주어졌을 때 동일한 문자를 포함하는 가장 긴 부분 문자열의 길이를 반환한다 문자는 최대 k번 변경할 수 있다`() { |
| 57 | + characterReplacement("ABAB", 2) shouldBe 4 |
| 58 | + characterReplacement("AABAB", 2) shouldBe 5 |
| 59 | + characterReplacement("AABAB", 1) shouldBe 4 |
| 60 | + characterReplacement("AABBAB", 1) shouldBe 4 |
| 61 | + } |
| 62 | +} |
0 commit comments