Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

코딩응급실

LeetCode: Longgest Common Prefix 본문

Java

LeetCode: Longgest Common Prefix

Daeryuk Kim 2024. 4. 3. 16:48
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) return "";
        
        // 첫 번째 문자열을 기준으로 삼습니다.
        String prefix = strs[0];
        
        // 첫 번째 문자열과 배열의 나머지 문자열들을 비교합니다.
        for (int i = 1; i < strs.length; i++) {
            // 현재 문자열에서 기준이 되는 접두사를 찾을 때까지 접두사의 길이를 줄입니다.
            while (strs[i].indexOf(prefix) != 0) {
                // 접두사를 하나씩 줄여나갑니다.
                prefix = prefix.substring(0, prefix.length() - 1);
                
                // 공통 접두사가 없으면 빈 문자열을 반환합니다.
                if (prefix.isEmpty()) return "";
            }
        }
        
        // 모든 문자열을 검사한 후 남은 접두사가 공통 접두사입니다.
        return prefix;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.longestCommonPrefix(new String[]{"flower","flow","flight"})); // 출력: "fl"
    }
}

'Java' 카테고리의 다른 글

프로그래머스 Lv.2: 호텔 대실  (0) 2024.12.04
프로그래머스: 마법의 엘리베이터  (0) 2024.10.15
LeetCode: Roman to Integer  (0) 2024.04.03
LeetCode: Two Sum  (0) 2024.04.03
LeetCode: Palindrome Number  (0) 2024.04.03