본문 바로가기
Beakjoon&프로그래머스/Java

[LeetCode/Java] 14. Longest Common Prefix

by 현장 2025. 11. 18.

-Code

class Solution {
    public String longestCommonPrefix(String[] strs) {
       int minStrLength = getMinLength(strs);
        int totalLength = strs.length;
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < minStrLength; i++) {
            // 첫 단어의 i번째 글자
            char first = strs[0].charAt(i);
            for (int j = 1; j < totalLength; j++) {
            	// 첫 단어의 글자와 다르면 바로 반환
                if (first != strs[j].charAt(i)) 
                    return sb.toString();
            }
            sb.append(first);
        }
        return sb.toString();
    }
    // 가장 짧은 단어 길이 찾기
    private int getMinLength(String[] strs) {
        int answer = Integer.MAX_VALUE;

        for (String str : strs) {
            answer = Math.min(str.length(), answer);
        }

        return answer;
    }
}