[ LeetCode ] 14 Longest Common Prefix

codesver·2023년 3월 26일
0

LeetCode

목록 보기
5/24
post-thumbnail

Link | LeetCode 14번 문제 : Longest Common Prefix

📌 About

가장 짧은 문자열을 찾은 이후에 각 문자를 차례대로 전체 문자열에서 탐색하면 된다.

📌 Solution

Step 1. 가장 짧은 문자열을 찾는다.

val min = strs.minBy { it.length }

Step 2. 가장 짧은 문자열의 문자를 하나씩 탐색한다.

min.forEachIndexed { idx, ch -> if (strs.all { it[idx] == ch }) 문자 추가 else 반환 }

📌 Code

GitHub Repository

fun longestCommonPrefix(strs: Array<String>) = StringBuilder().apply {
    strs.minBy { it.length }
        ?.forEachIndexed { idx, ch -> if (strs.all { it[idx] == ch }) append(ch) else return toString() }
}.toString()
profile
Hello, Devs!

0개의 댓글