(LeetCode) 14. Longest Common Prefix

Longest Common Prefix

  • Explore : Interview > Top Interveiw Questions > Easy Collection
  • 분류 : String
  • 난이도 : Easy

Problem

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

1
2
Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2

1
2
3
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 lower-case English letters.

Solution

Exapnder
1
2
3
4
5
6
7
8
9
class Solution {
fun longestCommonPrefix(strs: Array<String>): String {
if (strs.isNullOrEmpty()) {
return ""
}
strs.sort()
return strs[0].commonPrefixWith(strs[strs.size - 1])
}
}

Point of Thinking

  • 주어진 strs에 대한 null check로 early return
  • strs.sort()를 수행하고 처음과 끝에 있는 문자열의 공통 prefix를 반환하면 Accepted.