코틀린
-
유효한 괄호 문자열 확인Tech/Algorithm 2023. 10. 29. 13:12
fun isValidParentheses(s: String): Boolean { val stack = ArrayDeque() for (char in s) { when (char) { '(', '[', '{' -> stack.addLast(char) ')' -> if (stack.isEmpty() || stack.removeLast() != '(') return false ']' -> if (stack.isEmpty() || stack.removeLast() != '[') return false '}' -> if (stack.isEmpty() || stack.removeLast() != '{') return false } } return stack.isEmpty() } fun main() { println..
-
최빈 단어 찾기Tech/Algorithm 2023. 10. 29. 13:12
fun mostFrequentWord(s: String): Pair? { val words = s.split(' ') val frequencyMap = words.groupingBy { it }.eachCount() return frequencyMap.maxByOrNull { it.value } } fun main() { val (word, frequency) = mostFrequentWord("this is a sample program and it is a sample") ?: Pair("", 0) println("$word: $frequency") // "sample: 2" }