본문 바로가기
Computer/Algorithm

LeetCode - Longest Common Prefix

by HanDongWook 2022. 9. 30.
반응형

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.

풀이(Kotlin)

 - 문자가 한 개이면 그 문자를 리턴한다.

 - 문자가 두 개 이상일 경우 첫번째 문자를 기준으로 잡고 다음 문자와 prefix를 비교하고 prefix를 저장한다

 - prefix와 다음 문자를 비교하여 prefix를 저장한다.

 - 마지막 문자까지 진행한 후 prefix를 리턴한다.

class Solution {
    fun longestCommonPrefix(strs: Array<String>): String {
        if (strs.size == 1) return strs.first()
        var standard = strs[0]
        for (i in 1.. strs.lastIndex) {
            val next = strs[i]
            for (j in standard.indices) {
                if (j <= next.lastIndex) {
                    if (standard[j] != next[j]) {
                        standard = standard.filterIndexed { index, _ -> index < j }
                        break
                    }
                } else {
                    standard = standard.filterIndexed { index, _ -> index < j }
                    break
                }
            }
        }
        return standard
    }
}
반응형

'Computer > Algorithm' 카테고리의 다른 글

LeetCode - Binary Tree Preorder Traversal  (0) 2022.09.30
LeetCode - Binary Tree Inorder Traversal  (0) 2022.09.30
LeetCode - Valid Anagram  (0) 2022.09.30
백준 1406  (1) 2022.09.29
백준 2630  (1) 2022.09.29

댓글