본문 바로가기
LeetCode/Array & Hashing

[LeetCode][Kotlin] 14. Longest Common Prefix

by jinwo_o 2024. 10. 18.

14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

 

If there is no common prefix, return an empty string "".

문자열 배열 중에서 가장 긴 공통 접두사 문자열을 찾는 함수를 작성하세요. 

공통 접두사가 없으면 빈 문자열 ""을 반환합니다.

 

Example 1:

Input: strs = ["flower","flow","flight"]

Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]

Output: ""

Explanation: There is no common prefix among the input strings.

 

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters.

코드

class Solution {
    fun longestCommonPrefix(strs: Array<String>): String {
        var answer = ""

        for (i in strs[0].indices) {
            for (j in 1..strs.lastIndex) {
                if (i == strs[j].length || strs[0][i] != strs[j][i]) {
                    return answer
                }
            }
            answer += strs[0][i]
        }

        return answer
    }
}