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
}
}
'LeetCode > Array & Hashing' 카테고리의 다른 글
[LeetCode][Kotlin] 929. Unique Email Addresses (0) | 2024.10.18 |
---|---|
[LeetCode][Kotlin] 799. Champagne Tower (0) | 2024.09.25 |
[LeetCode][Kotlin] 2610. Convert an Array Into a 2D Array With Conditions (0) | 2024.09.25 |