문제 풀이 ✏️/기타

[프로그래머스] 468370 - 중요한 단어를 스포 방지

interfacer_han 2026. 8. 2. 16:18

문제 출처: 2025 카카오 하반기 1차

/* <헷갈리는 조건>
메시지의 스포 방지 구간이 아닌 구간
(= 어떤 스포 방지 구간에도 속하지 않는 모든 구간: 각 구간의 앞·사이·뒤 포함)
에 등장한 적이 없어야 합니다.
*/

const val START = 0
const val END = 1

class Solution {
    fun solution(message: String, spoiler_ranges: Array<IntArray>): Int {
        val wordValues = message.split(" ")
        val exposedWordValueSet = LinkedHashSet<String>()

        var startIndex = 0
        val words = Array(wordValues.size) {
            val wordValue = wordValues[it]
            
            val word = Word(wordValues[it], startIndex, startIndex + wordValue.length - 1)
            word.setSpoilerPrevented(spoiler_ranges)
            if (!word.isSpoilerPrevented) {
                exposedWordValueSet.add(word.value)
            }

            startIndex += wordValue.length + 1

            word
        }

        for (word in words) {
            if (!word.isSpoilerPrevented) {
                continue
            }

            if (exposedWordValueSet.contains(word.value)) {
                continue
            } else {
                exposedWordValueSet.add(word.value)
            }

            word.isImportant = true
        }

        return words.count { it.isImportant }
    }
}

class Word(val value: String, val startIndex: Int, val endIndex: Int) {
    var isSpoilerPrevented = false
    var isImportant = false

    fun setSpoilerPrevented(spoiler_ranges: Array<IntArray>) {
        for (spoiler_range in spoiler_ranges) {
            if ((startIndex <= spoiler_range[END]) && (endIndex >= spoiler_range[START])) {
                isSpoilerPrevented = true
                return
            }
        }
        isSpoilerPrevented = false
    }
}

실수로 많은 시간이 끌렸다. 앞으론 배열에서 원소를 꺼내쓰는 등의 코드를 쓸 때, 그걸 별도의 프로퍼티를 선언함으로써 한번 감싸줘야겠다 (잔실수 방지). 이런 자세가 '내 문제'에서 비롯된다고 스스로 비하해선 안 된다. 그저 내가 반복해서 겪는 상황을 있는 그대로 받아들이고, 중립적인 태도로 그저 대처할 뿐인 것이다.