본문 바로가기
알고리즘 문제풀이/leetcode

[leetcode 14] Longest Common Prefix

by m2162003 2020. 11. 13.

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:

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lower-case English letters.
class Solution {
    public String longestCommonPrefix(String[] strs) {
        
        int len = strs.length;
        if(len == 0){
            return "";
        }
        String cmp = strs[0];
        
        for(int i=1; i<len; i++){
            int l1 = cmp.length();
            int l2 = strs[i].length();
            
            int idx = 0;
            while(idx < Math.min(l1, l2)){
               if(cmp.charAt(idx) != strs[i].charAt(idx)){
                   break;
               } 
                idx++;
            }
            if(idx < l1){
                cmp = cmp.substring(0,idx);
            }
        }
        
        return cmp;
    }
}

댓글