본문 바로가기
Problem Solving/LeetCode

[LeetCode] 14. Longest Common Prefix - Java

by graycode 2026. 5. 11.

 문제 링크

 

Longest Common Prefix - LeetCode

Can you solve this real interview question? Longest Common Prefix - 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"

leetcode.com

 

 풀이 코드

public class Solution {

    public String longestCommonPrefix(String[] strs) {
        int min = 200;
        for (String s : strs) min = Math.min(min, s.length());

        for (int i = 0; i < min; i++)
            for (int j = 1; j < strs.length; j++)
                if (strs[0].charAt(i) != strs[j].charAt(i)) return strs[0].substring(0, i);

        return strs[0].substring(0, min);
    }

}

댓글